blob: 68089c2dd3600b09c9a689394c8158071ec614a3 [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)))
Reid Spencer612683b2006-12-13 08:33:33 +00002175 if (CI->getOperand(0)->getType() == Type::BoolTy &&
2176 CI->getOpcode() == Instruction::ZExt)
Chris Lattner2635b522004-02-23 05:39:21 +00002177 BoolCast = CI;
2178 if (!BoolCast)
2179 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
Reid Spencer612683b2006-12-13 08:33:33 +00002180 if (CI->getOperand(0)->getType() == Type::BoolTy &&
2181 CI->getOpcode() == Instruction::ZExt)
Chris Lattner2635b522004-02-23 05:39:21 +00002182 BoolCast = CI;
2183 if (BoolCast) {
2184 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2185 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2186 const Type *SCOpTy = SCIOp0->getType();
2187
Chris Lattnere79e8542004-02-23 06:38:22 +00002188 // If the setcc is true iff the sign bit of X is set, then convert this
2189 // multiply into a shift/and combination.
2190 if (isa<ConstantInt>(SCIOp1) &&
2191 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002192 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002193 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002194 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002195 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002196 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002197 SCIOp0 = InsertCastBefore(Instruction::BitCast, SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002198 }
2199
2200 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002201 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002202 BoolCast->getOperand(0)->getName()+
2203 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002204
2205 // If the multiply type is not the same as the source type, sign extend
2206 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002207 if (I.getType() != V->getType()) {
2208 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2209 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2210 Instruction::CastOps opcode =
2211 (SrcBits == DstBits ? Instruction::BitCast :
2212 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2213 V = InsertCastBefore(opcode, V, I.getType(), I);
2214 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002215
Chris Lattner2635b522004-02-23 05:39:21 +00002216 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002217 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002218 }
2219 }
2220 }
2221
Chris Lattner113f4f42002-06-25 16:13:24 +00002222 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002223}
2224
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002225/// This function implements the transforms on div instructions that work
2226/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2227/// used by the visitors to those instructions.
2228/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002229Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002231
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002232 // undef / X -> 0
2233 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002234 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002235
2236 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002237 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002238 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002239
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002240 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002241 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2242 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002243 // same basic block, then we replace the select with Y, and the condition
2244 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002245 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002246 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002247 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2248 if (ST->isNullValue()) {
2249 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2250 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002251 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002252 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2253 I.setOperand(1, SI->getOperand(2));
2254 else
2255 UpdateValueUsesWith(SI, SI->getOperand(2));
2256 return &I;
2257 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002258
Chris Lattnerd79dc792006-09-09 20:26:32 +00002259 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2260 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2261 if (ST->isNullValue()) {
2262 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2263 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002264 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002265 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2266 I.setOperand(1, SI->getOperand(1));
2267 else
2268 UpdateValueUsesWith(SI, SI->getOperand(1));
2269 return &I;
2270 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002272
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002273 return 0;
2274}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002275
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276/// This function implements the transforms common to both integer division
2277/// instructions (udiv and sdiv). It is called by the visitors to those integer
2278/// division instructions.
2279/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002280Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2282
2283 if (Instruction *Common = commonDivTransforms(I))
2284 return Common;
2285
2286 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2287 // div X, 1 == X
2288 if (RHS->equalsInt(1))
2289 return ReplaceInstUsesWith(I, Op0);
2290
2291 // (X / C1) / C2 -> X / (C1*C2)
2292 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2293 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2294 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2295 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2296 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002297 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002298
2299 if (!RHS->isNullValue()) { // avoid X udiv 0
2300 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2301 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2302 return R;
2303 if (isa<PHINode>(Op0))
2304 if (Instruction *NV = FoldOpIntoPhi(I))
2305 return NV;
2306 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002307 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002308
Chris Lattner3082c5a2003-02-18 19:28:33 +00002309 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002310 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002311 if (LHS->equalsInt(0))
2312 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2313
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002314 return 0;
2315}
2316
2317Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2318 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2319
2320 // Handle the integer div common cases
2321 if (Instruction *Common = commonIDivTransforms(I))
2322 return Common;
2323
2324 // X udiv C^2 -> X >> C
2325 // Check to see if this is an unsigned division with an exact power of 2,
2326 // if so, convert to a right shift.
2327 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2328 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2329 if (isPowerOf2_64(Val)) {
2330 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002331 return new ShiftInst(Instruction::LShr, Op0,
2332 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002333 }
2334 }
2335
2336 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2337 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2338 if (RHSI->getOpcode() == Instruction::Shl &&
2339 isa<ConstantInt>(RHSI->getOperand(0))) {
2340 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2341 if (isPowerOf2_64(C1)) {
2342 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002343 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002344 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002345 Constant *C2V = ConstantInt::get(NTy, C2);
2346 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002347 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002348 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002349 }
2350 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002351 }
2352
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002353 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2354 // where C1&C2 are powers of two.
2355 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2356 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2357 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2358 if (!STO->isNullValue() && !STO->isNullValue()) {
2359 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2360 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2361 // Compute the shift amounts
2362 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002363 // Construct the "on true" case of the select
2364 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2365 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002366 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002367 TSI = InsertNewInstBefore(TSI, I);
2368
2369 // Construct the "on false" case of the select
2370 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2371 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002373 FSI = InsertNewInstBefore(FSI, I);
2374
2375 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002376 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 }
2378 }
2379 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002380 return 0;
2381}
2382
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002383Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2385
2386 // Handle the integer div common cases
2387 if (Instruction *Common = commonIDivTransforms(I))
2388 return Common;
2389
2390 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2391 // sdiv X, -1 == -X
2392 if (RHS->isAllOnesValue())
2393 return BinaryOperator::createNeg(Op0);
2394
2395 // -X/C -> X/-C
2396 if (Value *LHSNeg = dyn_castNegVal(Op0))
2397 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2398 }
2399
2400 // If the sign bits of both operands are zero (i.e. we can prove they are
2401 // unsigned inputs), turn this into a udiv.
2402 if (I.getType()->isInteger()) {
2403 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2404 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2405 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2406 }
2407 }
2408
2409 return 0;
2410}
2411
2412Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2413 return commonDivTransforms(I);
2414}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002415
Chris Lattner85dda9a2006-03-02 06:50:58 +00002416/// GetFactor - If we can prove that the specified value is at least a multiple
2417/// of some factor, return that factor.
2418static Constant *GetFactor(Value *V) {
2419 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2420 return CI;
2421
2422 // Unless we can be tricky, we know this is a multiple of 1.
2423 Constant *Result = ConstantInt::get(V->getType(), 1);
2424
2425 Instruction *I = dyn_cast<Instruction>(V);
2426 if (!I) return Result;
2427
2428 if (I->getOpcode() == Instruction::Mul) {
2429 // Handle multiplies by a constant, etc.
2430 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2431 GetFactor(I->getOperand(1)));
2432 } else if (I->getOpcode() == Instruction::Shl) {
2433 // (X<<C) -> X * (1 << C)
2434 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2435 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2436 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2437 }
2438 } else if (I->getOpcode() == Instruction::And) {
2439 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2440 // X & 0xFFF0 is known to be a multiple of 16.
2441 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2442 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2443 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002444 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002445 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002446 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002447 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002448 if (!CI->isIntegerCast())
2449 return Result;
2450 Value *Op = CI->getOperand(0);
2451 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002452 }
2453 return Result;
2454}
2455
Reid Spencer7eb55b32006-11-02 01:53:59 +00002456/// This function implements the transforms on rem instructions that work
2457/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2458/// is used by the visitors to those instructions.
2459/// @brief Transforms common to all three rem instructions
2460Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002462
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002463 // 0 % X == 0, we don't need to preserve faults!
2464 if (Constant *LHS = dyn_cast<Constant>(Op0))
2465 if (LHS->isNullValue())
2466 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2467
2468 if (isa<UndefValue>(Op0)) // undef % X -> 0
2469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2470 if (isa<UndefValue>(Op1))
2471 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002472
2473 // Handle cases involving: rem X, (select Cond, Y, Z)
2474 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2475 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2476 // the same basic block, then we replace the select with Y, and the
2477 // condition of the select with false (if the cond value is in the same
2478 // BB). If the select has uses other than the div, this allows them to be
2479 // simplified also.
2480 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2481 if (ST->isNullValue()) {
2482 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2483 if (CondI && CondI->getParent() == I.getParent())
2484 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2485 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2486 I.setOperand(1, SI->getOperand(2));
2487 else
2488 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002489 return &I;
2490 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002491 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2492 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2493 if (ST->isNullValue()) {
2494 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2495 if (CondI && CondI->getParent() == I.getParent())
2496 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2497 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2498 I.setOperand(1, SI->getOperand(1));
2499 else
2500 UpdateValueUsesWith(SI, SI->getOperand(1));
2501 return &I;
2502 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002503 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002504
Reid Spencer7eb55b32006-11-02 01:53:59 +00002505 return 0;
2506}
2507
2508/// This function implements the transforms common to both integer remainder
2509/// instructions (urem and srem). It is called by the visitors to those integer
2510/// remainder instructions.
2511/// @brief Common integer remainder transforms
2512Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2514
2515 if (Instruction *common = commonRemTransforms(I))
2516 return common;
2517
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002518 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002519 // X % 0 == undef, we don't need to preserve faults!
2520 if (RHS->equalsInt(0))
2521 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2522
Chris Lattner3082c5a2003-02-18 19:28:33 +00002523 if (RHS->equalsInt(1)) // X % 1 == 0
2524 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2525
Chris Lattnerb70f1412006-02-28 05:49:21 +00002526 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2527 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2528 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2529 return R;
2530 } else if (isa<PHINode>(Op0I)) {
2531 if (Instruction *NV = FoldOpIntoPhi(I))
2532 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002533 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002534 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2535 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002536 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002537 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002538 }
2539
Reid Spencer7eb55b32006-11-02 01:53:59 +00002540 return 0;
2541}
2542
2543Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2544 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2545
2546 if (Instruction *common = commonIRemTransforms(I))
2547 return common;
2548
2549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2550 // X urem C^2 -> X and C
2551 // Check to see if this is an unsigned remainder with an exact power of 2,
2552 // if so, convert to a bitwise and.
2553 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2554 if (isPowerOf2_64(C->getZExtValue()))
2555 return BinaryOperator::createAnd(Op0, SubOne(C));
2556 }
2557
Chris Lattner2e90b732006-02-05 07:54:04 +00002558 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002559 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2560 if (RHSI->getOpcode() == Instruction::Shl &&
2561 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002562 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002563 if (isPowerOf2_64(C1)) {
2564 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2565 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2566 "tmp"), I);
2567 return BinaryOperator::createAnd(Op0, Add);
2568 }
2569 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002570 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002571
Reid Spencer7eb55b32006-11-02 01:53:59 +00002572 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2573 // where C1&C2 are powers of two.
2574 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2575 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2576 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2577 // STO == 0 and SFO == 0 handled above.
2578 if (isPowerOf2_64(STO->getZExtValue()) &&
2579 isPowerOf2_64(SFO->getZExtValue())) {
2580 Value *TrueAnd = InsertNewInstBefore(
2581 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2582 Value *FalseAnd = InsertNewInstBefore(
2583 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2584 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2585 }
2586 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002587 }
2588
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002589 return 0;
2590}
2591
Reid Spencer7eb55b32006-11-02 01:53:59 +00002592Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2593 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2594
2595 if (Instruction *common = commonIRemTransforms(I))
2596 return common;
2597
2598 if (Value *RHSNeg = dyn_castNegVal(Op1))
2599 if (!isa<ConstantInt>(RHSNeg) ||
2600 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2601 // X % -Y -> X % Y
2602 AddUsesToWorkList(I);
2603 I.setOperand(1, RHSNeg);
2604 return &I;
2605 }
2606
2607 // If the top bits of both operands are zero (i.e. we can prove they are
2608 // unsigned inputs), turn this into a urem.
2609 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2610 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2611 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2612 return BinaryOperator::createURem(Op0, Op1, I.getName());
2613 }
2614
2615 return 0;
2616}
2617
2618Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002619 return commonRemTransforms(I);
2620}
2621
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002622// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002623static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002624 if (C->getType()->isUnsigned())
2625 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002626
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002627 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002628 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002629 int64_t Val = INT64_MAX; // All ones
2630 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002631 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002632}
2633
2634// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002635static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002636 if (C->getType()->isUnsigned())
2637 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002638
2639 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002640 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002641 int64_t Val = -1; // All ones
2642 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002643 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002644}
2645
Chris Lattner35167c32004-06-09 07:59:58 +00002646// isOneBitSet - Return true if there is exactly one bit set in the specified
2647// constant.
2648static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002649 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002650 return V && (V & (V-1)) == 0;
2651}
2652
Chris Lattner8fc5af42004-09-23 21:46:38 +00002653#if 0 // Currently unused
2654// isLowOnes - Return true if the constant is of the form 0+1+.
2655static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002656 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002657
2658 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002659 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002660
2661 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2662 return U && V && (U & V) == 0;
2663}
2664#endif
2665
2666// isHighOnes - Return true if the constant is of the form 1+0+.
2667// This is the same as lowones(~X).
2668static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002669 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002670 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002671
2672 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002673 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002674
2675 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2676 return U && V && (U & V) == 0;
2677}
2678
2679
Chris Lattner3ac7c262003-08-13 20:16:26 +00002680/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2681/// are carefully arranged to allow folding of expressions such as:
2682///
2683/// (A < B) | (A > B) --> (A != B)
2684///
2685/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2686/// represents that the comparison is true if A == B, and bit value '1' is true
2687/// if A < B.
2688///
2689static unsigned getSetCondCode(const SetCondInst *SCI) {
2690 switch (SCI->getOpcode()) {
2691 // False -> 0
2692 case Instruction::SetGT: return 1;
2693 case Instruction::SetEQ: return 2;
2694 case Instruction::SetGE: return 3;
2695 case Instruction::SetLT: return 4;
2696 case Instruction::SetNE: return 5;
2697 case Instruction::SetLE: return 6;
2698 // True -> 7
2699 default:
2700 assert(0 && "Invalid SetCC opcode!");
2701 return 0;
2702 }
2703}
2704
2705/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2706/// opcode and two operands into either a constant true or false, or a brand new
2707/// SetCC instruction.
2708static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2709 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002710 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002711 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2712 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2713 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2714 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2715 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2716 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002717 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002718 default: assert(0 && "Illegal SetCCCode!"); return 0;
2719 }
2720}
2721
2722// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnere3a63d12006-11-15 04:53:24 +00002723namespace {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002724struct FoldSetCCLogical {
2725 InstCombiner &IC;
2726 Value *LHS, *RHS;
2727 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2728 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2729 bool shouldApply(Value *V) const {
2730 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2731 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2732 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2733 return false;
2734 }
2735 Instruction *apply(BinaryOperator &Log) const {
2736 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2737 if (SCI->getOperand(0) != LHS) {
2738 assert(SCI->getOperand(1) == LHS);
2739 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2740 }
2741
2742 unsigned LHSCode = getSetCondCode(SCI);
2743 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2744 unsigned Code;
2745 switch (Log.getOpcode()) {
2746 case Instruction::And: Code = LHSCode & RHSCode; break;
2747 case Instruction::Or: Code = LHSCode | RHSCode; break;
2748 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002749 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002750 }
2751
2752 Value *RV = getSetCCValue(Code, LHS, RHS);
2753 if (Instruction *I = dyn_cast<Instruction>(RV))
2754 return I;
2755 // Otherwise, it's a constant boolean value...
2756 return IC.ReplaceInstUsesWith(Log, RV);
2757 }
2758};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002759} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002760
Chris Lattnerba1cb382003-09-19 17:17:26 +00002761// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2762// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2763// guaranteed to be either a shift instruction or a binary operator.
2764Instruction *InstCombiner::OptAndOp(Instruction *Op,
2765 ConstantIntegral *OpRHS,
2766 ConstantIntegral *AndRHS,
2767 BinaryOperator &TheAnd) {
2768 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002769 Constant *Together = 0;
2770 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002771 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002772
Chris Lattnerba1cb382003-09-19 17:17:26 +00002773 switch (Op->getOpcode()) {
2774 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002775 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002776 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2777 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002778 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002779 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002780 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002781 }
2782 break;
2783 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002784 if (Together == AndRHS) // (X | C) & C --> C
2785 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002786
Chris Lattner86102b82005-01-01 16:22:27 +00002787 if (Op->hasOneUse() && Together != OpRHS) {
2788 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2789 std::string Op0Name = Op->getName(); Op->setName("");
2790 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2791 InsertNewInstBefore(Or, TheAnd);
2792 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002793 }
2794 break;
2795 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002796 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002797 // Adding a one to a single bit bit-field should be turned into an XOR
2798 // of the bit. First thing to check is to see if this AND is with a
2799 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002800 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002801
2802 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002803 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002804
2805 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002806 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002807 // Ok, at this point, we know that we are masking the result of the
2808 // ADD down to exactly one bit. If the constant we are adding has
2809 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002810 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002811
Chris Lattnerba1cb382003-09-19 17:17:26 +00002812 // Check to see if any bits below the one bit set in AndRHSV are set.
2813 if ((AddRHS & (AndRHSV-1)) == 0) {
2814 // If not, the only thing that can effect the output of the AND is
2815 // the bit specified by AndRHSV. If that bit is set, the effect of
2816 // the XOR is to toggle the bit. If it is clear, then the ADD has
2817 // no effect.
2818 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2819 TheAnd.setOperand(0, X);
2820 return &TheAnd;
2821 } else {
2822 std::string Name = Op->getName(); Op->setName("");
2823 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002824 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002825 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002826 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002827 }
2828 }
2829 }
2830 }
2831 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002832
2833 case Instruction::Shl: {
2834 // We know that the AND will not produce any of the bits shifted in, so if
2835 // the anded constant includes them, clear them now!
2836 //
2837 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002838 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2839 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002840
Chris Lattner7e794272004-09-24 15:21:34 +00002841 if (CI == ShlMask) { // Masking out bits that the shift already masks
2842 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2843 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002844 TheAnd.setOperand(1, CI);
2845 return &TheAnd;
2846 }
2847 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002848 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002849 case Instruction::LShr:
2850 {
Chris Lattner2da29172003-09-19 19:05:02 +00002851 // We know that the AND will not produce any of the bits shifted in, so if
2852 // the anded constant includes them, clear them now! This only applies to
2853 // unsigned shifts, because a signed shr may bring in set bits!
2854 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002855 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2856 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2857 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002858
Reid Spencerfdff9382006-11-08 06:47:33 +00002859 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2860 return ReplaceInstUsesWith(TheAnd, Op);
2861 } else if (CI != AndRHS) {
2862 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2863 return &TheAnd;
2864 }
2865 break;
2866 }
2867 case Instruction::AShr:
2868 // Signed shr.
2869 // See if this is shifting in some sign extension, then masking it out
2870 // with an and.
2871 if (Op->hasOneUse()) {
2872 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2873 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2874 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2875 if (CI == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002876 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002877 // Make the argument unsigned.
2878 Value *ShVal = Op->getOperand(0);
2879 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2880 OpRHS, Op->getName()),
2881 TheAnd);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002882 Value *AndRHS2 = ConstantExpr::getBitCast(AndRHS, ShVal->getType());
2883
Reid Spencerfdff9382006-11-08 06:47:33 +00002884 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002885 }
Chris Lattner2da29172003-09-19 19:05:02 +00002886 }
2887 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002888 }
2889 return 0;
2890}
2891
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002892
Chris Lattner6862fbd2004-09-29 17:40:11 +00002893/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2894/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2895/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2896/// insert new instructions.
2897Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2898 bool Inside, Instruction &IB) {
2899 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2900 "Lo is not <= Hi in range emission code!");
2901 if (Inside) {
2902 if (Lo == Hi) // Trivially false.
2903 return new SetCondInst(Instruction::SetNE, V, V);
Reid Spencer4ae56f32006-12-06 20:39:57 +00002904 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002905 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002906
Chris Lattner6862fbd2004-09-29 17:40:11 +00002907 Constant *AddCST = ConstantExpr::getNeg(Lo);
2908 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2909 InsertNewInstBefore(Add, IB);
2910 // Convert to unsigned for the comparison.
2911 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002912 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002913 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002914 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002915 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2916 }
2917
2918 if (Lo == Hi) // Trivially true.
2919 return new SetCondInst(Instruction::SetEQ, V, V);
2920
2921 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002922
2923 // V < 0 || V >= Hi ->'V > Hi-1'
Reid Spencer4ae56f32006-12-06 20:39:57 +00002924 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002925 return new SetCondInst(Instruction::SetGT, V, Hi);
2926
2927 // Emit X-Lo > Hi-Lo-1
2928 Constant *AddCST = ConstantExpr::getNeg(Lo);
2929 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2930 InsertNewInstBefore(Add, IB);
2931 // Convert to unsigned for the comparison.
2932 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002933 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002934 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002935 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002936 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2937}
2938
Chris Lattnerb4b25302005-09-18 07:22:02 +00002939// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2940// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2941// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2942// not, since all 1s are not contiguous.
2943static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002944 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002945 if (!isShiftedMask_64(V)) return false;
2946
2947 // look for the first zero bit after the run of ones
2948 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2949 // look for the first non-zero bit
2950 ME = 64-CountLeadingZeros_64(V);
2951 return true;
2952}
2953
2954
2955
2956/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2957/// where isSub determines whether the operator is a sub. If we can fold one of
2958/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002959///
2960/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2961/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2962/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2963///
2964/// return (A +/- B).
2965///
2966Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2967 ConstantIntegral *Mask, bool isSub,
2968 Instruction &I) {
2969 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2970 if (!LHSI || LHSI->getNumOperands() != 2 ||
2971 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2972
2973 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2974
2975 switch (LHSI->getOpcode()) {
2976 default: return 0;
2977 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002978 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2979 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002980 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002981 break;
2982
2983 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2984 // part, we don't need any explicit masks to take them out of A. If that
2985 // is all N is, ignore it.
2986 unsigned MB, ME;
2987 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002988 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2989 Mask >>= 64-MB+1;
2990 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002991 break;
2992 }
2993 }
Chris Lattneraf517572005-09-18 04:24:45 +00002994 return 0;
2995 case Instruction::Or:
2996 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002997 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002998 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002999 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003000 break;
3001 return 0;
3002 }
3003
3004 Instruction *New;
3005 if (isSub)
3006 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3007 else
3008 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3009 return InsertNewInstBefore(New, I);
3010}
3011
Chris Lattner113f4f42002-06-25 16:13:24 +00003012Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003013 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003015
Chris Lattner81a7a232004-10-16 18:11:37 +00003016 if (isa<UndefValue>(Op1)) // X & undef -> 0
3017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3018
Chris Lattner86102b82005-01-01 16:22:27 +00003019 // and X, X = X
3020 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003021 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003022
Chris Lattner5b2edb12006-02-12 08:02:11 +00003023 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003024 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003025 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003026 if (!isa<PackedType>(I.getType()) &&
3027 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003028 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003029 return &I;
3030
Chris Lattner86102b82005-01-01 16:22:27 +00003031 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003032 uint64_t AndRHSMask = AndRHS->getZExtValue();
3033 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003034 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003035
Chris Lattnerba1cb382003-09-19 17:17:26 +00003036 // Optimize a variety of ((val OP C1) & C2) combinations...
3037 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3038 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003039 Value *Op0LHS = Op0I->getOperand(0);
3040 Value *Op0RHS = Op0I->getOperand(1);
3041 switch (Op0I->getOpcode()) {
3042 case Instruction::Xor:
3043 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003044 // If the mask is only needed on one incoming arm, push it up.
3045 if (Op0I->hasOneUse()) {
3046 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3047 // Not masking anything out for the LHS, move to RHS.
3048 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3049 Op0RHS->getName()+".masked");
3050 InsertNewInstBefore(NewRHS, I);
3051 return BinaryOperator::create(
3052 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003053 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003054 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003055 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3056 // Not masking anything out for the RHS, move to LHS.
3057 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3058 Op0LHS->getName()+".masked");
3059 InsertNewInstBefore(NewLHS, I);
3060 return BinaryOperator::create(
3061 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3062 }
3063 }
3064
Chris Lattner86102b82005-01-01 16:22:27 +00003065 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003066 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003067 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3068 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3069 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3070 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3071 return BinaryOperator::createAnd(V, AndRHS);
3072 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3073 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003074 break;
3075
3076 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003077 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3078 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3079 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3080 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3081 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003082 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003083 }
3084
Chris Lattner16464b32003-07-23 19:25:52 +00003085 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003086 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003087 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003088 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003089 // If this is an integer truncation or change from signed-to-unsigned, and
3090 // if the source is an and/or with immediate, transform it. This
3091 // frequently occurs for bitfield accesses.
3092 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003093 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003094 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003095 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003096 if (CastOp->getOpcode() == Instruction::And) {
3097 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003098 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3099 // This will fold the two constants together, which may allow
3100 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003101 Instruction *NewCast = CastInst::createTruncOrBitCast(
3102 CastOp->getOperand(0), I.getType(),
3103 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003104 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003105 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003106 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003107 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003108 return BinaryOperator::createAnd(NewCast, C3);
3109 } else if (CastOp->getOpcode() == Instruction::Or) {
3110 // Change: and (cast (or X, C1) to T), C2
3111 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003112 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003113 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3114 return ReplaceInstUsesWith(I, AndRHS);
3115 }
3116 }
Chris Lattner33217db2003-07-23 19:36:21 +00003117 }
Chris Lattner183b3362004-04-09 19:05:30 +00003118
3119 // Try to fold constant and into select arguments.
3120 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003121 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003122 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003123 if (isa<PHINode>(Op0))
3124 if (Instruction *NV = FoldOpIntoPhi(I))
3125 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003126 }
3127
Chris Lattnerbb74e222003-03-10 23:06:50 +00003128 Value *Op0NotVal = dyn_castNotVal(Op0);
3129 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003130
Chris Lattner023a4832004-06-18 06:07:51 +00003131 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3133
Misha Brukman9c003d82004-07-30 12:50:08 +00003134 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003135 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003136 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3137 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003138 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003139 return BinaryOperator::createNot(Or);
3140 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003141
3142 {
3143 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003144 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3145 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3146 return ReplaceInstUsesWith(I, Op1);
3147 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3148 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3149 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003150
3151 if (Op0->hasOneUse() &&
3152 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3153 if (A == Op1) { // (A^B)&A -> A&(A^B)
3154 I.swapOperands(); // Simplify below
3155 std::swap(Op0, Op1);
3156 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3157 cast<BinaryOperator>(Op0)->swapOperands();
3158 I.swapOperands(); // Simplify below
3159 std::swap(Op0, Op1);
3160 }
3161 }
3162 if (Op1->hasOneUse() &&
3163 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3164 if (B == Op0) { // B&(A^B) -> B&(B^A)
3165 cast<BinaryOperator>(Op1)->swapOperands();
3166 std::swap(A, B);
3167 }
3168 if (A == Op0) { // A&(A^B) -> A & ~B
3169 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3170 InsertNewInstBefore(NotB, I);
3171 return BinaryOperator::createAnd(A, NotB);
3172 }
3173 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003174 }
3175
Chris Lattner3082c5a2003-02-18 19:28:33 +00003176
Chris Lattner623826c2004-09-28 21:48:02 +00003177 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3178 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003179 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3180 return R;
3181
Chris Lattner623826c2004-09-28 21:48:02 +00003182 Value *LHSVal, *RHSVal;
3183 ConstantInt *LHSCst, *RHSCst;
3184 Instruction::BinaryOps LHSCC, RHSCC;
3185 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3186 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3187 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3188 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003189 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003190 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3191 // Ensure that the larger constant is on the RHS.
3192 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3193 SetCondInst *LHS = cast<SetCondInst>(Op0);
3194 if (cast<ConstantBool>(Cmp)->getValue()) {
3195 std::swap(LHS, RHS);
3196 std::swap(LHSCst, RHSCst);
3197 std::swap(LHSCC, RHSCC);
3198 }
3199
3200 // At this point, we know we have have two setcc instructions
3201 // comparing a value against two constants and and'ing the result
3202 // together. Because of the above check, we know that we only have
3203 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3204 // FoldSetCCLogical check above), that the two constants are not
3205 // equal.
3206 assert(LHSCst != RHSCst && "Compares not folded above?");
3207
3208 switch (LHSCC) {
3209 default: assert(0 && "Unknown integer condition code!");
3210 case Instruction::SetEQ:
3211 switch (RHSCC) {
3212 default: assert(0 && "Unknown integer condition code!");
3213 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3214 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003215 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003216 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3217 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3218 return ReplaceInstUsesWith(I, LHS);
3219 }
3220 case Instruction::SetNE:
3221 switch (RHSCC) {
3222 default: assert(0 && "Unknown integer condition code!");
3223 case Instruction::SetLT:
3224 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3225 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3226 break; // (X != 13 & X < 15) -> no change
3227 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3228 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3229 return ReplaceInstUsesWith(I, RHS);
3230 case Instruction::SetNE:
3231 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3232 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3233 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3234 LHSVal->getName()+".off");
3235 InsertNewInstBefore(Add, I);
3236 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003237 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3238 UnsType, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003239 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003240 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner623826c2004-09-28 21:48:02 +00003241 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3242 }
3243 break; // (X != 13 & X != 15) -> no change
3244 }
3245 break;
3246 case Instruction::SetLT:
3247 switch (RHSCC) {
3248 default: assert(0 && "Unknown integer condition code!");
3249 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3250 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003251 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003252 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3253 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3254 return ReplaceInstUsesWith(I, LHS);
3255 }
3256 case Instruction::SetGT:
3257 switch (RHSCC) {
3258 default: assert(0 && "Unknown integer condition code!");
3259 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3260 return ReplaceInstUsesWith(I, LHS);
3261 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3262 return ReplaceInstUsesWith(I, RHS);
3263 case Instruction::SetNE:
3264 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3265 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3266 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003267 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3268 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003269 }
3270 }
3271 }
3272 }
3273
Chris Lattner3af10532006-05-05 06:39:07 +00003274 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003275 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3276 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3277 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3278 const Type *SrcTy = Op0C->getOperand(0)->getType();
3279 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3280 // Only do this if the casts both really cause code to be generated.
3281 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3282 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3283 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3284 Op1C->getOperand(0),
3285 I.getName());
3286 InsertNewInstBefore(NewOp, I);
3287 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3288 }
Chris Lattner3af10532006-05-05 06:39:07 +00003289 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003290
3291 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3292 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3293 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3294 if (SI0->getOpcode() == SI1->getOpcode() &&
3295 SI0->getOperand(1) == SI1->getOperand(1) &&
3296 (SI0->hasOneUse() || SI1->hasOneUse())) {
3297 Instruction *NewOp =
3298 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3299 SI1->getOperand(0),
3300 SI0->getName()), I);
3301 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3302 }
Chris Lattner3af10532006-05-05 06:39:07 +00003303 }
3304
Chris Lattner113f4f42002-06-25 16:13:24 +00003305 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003306}
3307
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003308/// CollectBSwapParts - Look to see if the specified value defines a single byte
3309/// in the result. If it does, and if the specified byte hasn't been filled in
3310/// yet, fill it in and return false.
3311static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3312 Instruction *I = dyn_cast<Instruction>(V);
3313 if (I == 0) return true;
3314
3315 // If this is an or instruction, it is an inner node of the bswap.
3316 if (I->getOpcode() == Instruction::Or)
3317 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3318 CollectBSwapParts(I->getOperand(1), ByteValues);
3319
3320 // If this is a shift by a constant int, and it is "24", then its operand
3321 // defines a byte. We only handle unsigned types here.
3322 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3323 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003324 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003325 8*(ByteValues.size()-1))
3326 return true;
3327
3328 unsigned DestNo;
3329 if (I->getOpcode() == Instruction::Shl) {
3330 // X << 24 defines the top byte with the lowest of the input bytes.
3331 DestNo = ByteValues.size()-1;
3332 } else {
3333 // X >>u 24 defines the low byte with the highest of the input bytes.
3334 DestNo = 0;
3335 }
3336
3337 // If the destination byte value is already defined, the values are or'd
3338 // together, which isn't a bswap (unless it's an or of the same bits).
3339 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3340 return true;
3341 ByteValues[DestNo] = I->getOperand(0);
3342 return false;
3343 }
3344
3345 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3346 // don't have this.
3347 Value *Shift = 0, *ShiftLHS = 0;
3348 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3349 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3350 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3351 return true;
3352 Instruction *SI = cast<Instruction>(Shift);
3353
3354 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003355 if (ShiftAmt->getZExtValue() & 7 ||
3356 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003357 return true;
3358
3359 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3360 unsigned DestByte;
3361 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003362 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003363 break;
3364 // Unknown mask for bswap.
3365 if (DestByte == ByteValues.size()) return true;
3366
Reid Spencere0fc4df2006-10-20 07:07:24 +00003367 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003368 unsigned SrcByte;
3369 if (SI->getOpcode() == Instruction::Shl)
3370 SrcByte = DestByte - ShiftBytes;
3371 else
3372 SrcByte = DestByte + ShiftBytes;
3373
3374 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3375 if (SrcByte != ByteValues.size()-DestByte-1)
3376 return true;
3377
3378 // If the destination byte value is already defined, the values are or'd
3379 // together, which isn't a bswap (unless it's an or of the same bits).
3380 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3381 return true;
3382 ByteValues[DestByte] = SI->getOperand(0);
3383 return false;
3384}
3385
3386/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3387/// If so, insert the new bswap intrinsic and return it.
3388Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3389 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3390 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3391 return 0;
3392
3393 /// ByteValues - For each byte of the result, we keep track of which value
3394 /// defines each byte.
3395 std::vector<Value*> ByteValues;
3396 ByteValues.resize(I.getType()->getPrimitiveSize());
3397
3398 // Try to find all the pieces corresponding to the bswap.
3399 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3400 CollectBSwapParts(I.getOperand(1), ByteValues))
3401 return 0;
3402
3403 // Check to see if all of the bytes come from the same value.
3404 Value *V = ByteValues[0];
3405 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3406
3407 // Check to make sure that all of the bytes come from the same value.
3408 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3409 if (ByteValues[i] != V)
3410 return 0;
3411
3412 // If they do then *success* we can turn this into a bswap. Figure out what
3413 // bswap to make it into.
3414 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003415 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003416 if (I.getType() == Type::UShortTy)
3417 FnName = "llvm.bswap.i16";
3418 else if (I.getType() == Type::UIntTy)
3419 FnName = "llvm.bswap.i32";
3420 else if (I.getType() == Type::ULongTy)
3421 FnName = "llvm.bswap.i64";
3422 else
3423 assert(0 && "Unknown integer type!");
3424 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3425
3426 return new CallInst(F, V);
3427}
3428
3429
Chris Lattner113f4f42002-06-25 16:13:24 +00003430Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003431 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003432 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003433
Chris Lattner81a7a232004-10-16 18:11:37 +00003434 if (isa<UndefValue>(Op1))
3435 return ReplaceInstUsesWith(I, // X | undef -> -1
3436 ConstantIntegral::getAllOnesValue(I.getType()));
3437
Chris Lattner5b2edb12006-02-12 08:02:11 +00003438 // or X, X = X
3439 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003440 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003441
Chris Lattner5b2edb12006-02-12 08:02:11 +00003442 // See if we can simplify any instructions used by the instruction whose sole
3443 // purpose is to compute bits we don't care about.
3444 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003445 if (!isa<PackedType>(I.getType()) &&
3446 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003447 KnownZero, KnownOne))
3448 return &I;
3449
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003450 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003451 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003452 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003453 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3454 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003455 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3456 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003457 InsertNewInstBefore(Or, I);
3458 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3459 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003460
Chris Lattnerd4252a72004-07-30 07:50:03 +00003461 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3462 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3463 std::string Op0Name = Op0->getName(); Op0->setName("");
3464 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3465 InsertNewInstBefore(Or, I);
3466 return BinaryOperator::createXor(Or,
3467 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003468 }
Chris Lattner183b3362004-04-09 19:05:30 +00003469
3470 // Try to fold constant and into select arguments.
3471 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003472 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003473 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003474 if (isa<PHINode>(Op0))
3475 if (Instruction *NV = FoldOpIntoPhi(I))
3476 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003477 }
3478
Chris Lattner330628a2006-01-06 17:59:59 +00003479 Value *A = 0, *B = 0;
3480 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003481
3482 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3483 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3484 return ReplaceInstUsesWith(I, Op1);
3485 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3486 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3487 return ReplaceInstUsesWith(I, Op0);
3488
Chris Lattnerb7845d62006-07-10 20:25:24 +00003489 // (A | B) | C and A | (B | C) -> bswap if possible.
3490 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003491 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003492 match(Op1, m_Or(m_Value(), m_Value())) ||
3493 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3494 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003495 if (Instruction *BSwap = MatchBSwap(I))
3496 return BSwap;
3497 }
3498
Chris Lattnerb62f5082005-05-09 04:58:36 +00003499 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3500 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003501 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003502 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3503 Op0->setName("");
3504 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3505 }
3506
3507 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3508 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003509 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003510 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3511 Op0->setName("");
3512 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3513 }
3514
Chris Lattner15212982005-09-18 03:42:07 +00003515 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003516 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003517 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3518
3519 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3520 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3521
3522
Chris Lattner01f56c62005-09-18 06:02:59 +00003523 // If we have: ((V + N) & C1) | (V & C2)
3524 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3525 // replace with V+N.
3526 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003527 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003528 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003529 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3530 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003531 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003532 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003533 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003534 return ReplaceInstUsesWith(I, A);
3535 }
3536 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003537 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003538 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3539 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003540 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003541 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003542 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003543 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003544 }
3545 }
3546 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003547
3548 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3549 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3550 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3551 if (SI0->getOpcode() == SI1->getOpcode() &&
3552 SI0->getOperand(1) == SI1->getOperand(1) &&
3553 (SI0->hasOneUse() || SI1->hasOneUse())) {
3554 Instruction *NewOp =
3555 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3556 SI1->getOperand(0),
3557 SI0->getName()), I);
3558 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3559 }
3560 }
Chris Lattner812aab72003-08-12 19:11:07 +00003561
Chris Lattnerd4252a72004-07-30 07:50:03 +00003562 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3563 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003564 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003565 ConstantIntegral::getAllOnesValue(I.getType()));
3566 } else {
3567 A = 0;
3568 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003569 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003570 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3571 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003572 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003573 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003574
Misha Brukman9c003d82004-07-30 12:50:08 +00003575 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003576 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3577 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3578 I.getName()+".demorgan"), I);
3579 return BinaryOperator::createNot(And);
3580 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003581 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003582
Chris Lattner3ac7c262003-08-13 20:16:26 +00003583 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003584 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003585 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3586 return R;
3587
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003588 Value *LHSVal, *RHSVal;
3589 ConstantInt *LHSCst, *RHSCst;
3590 Instruction::BinaryOps LHSCC, RHSCC;
3591 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3592 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3593 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3594 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003595 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003596 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3597 // Ensure that the larger constant is on the RHS.
3598 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3599 SetCondInst *LHS = cast<SetCondInst>(Op0);
3600 if (cast<ConstantBool>(Cmp)->getValue()) {
3601 std::swap(LHS, RHS);
3602 std::swap(LHSCst, RHSCst);
3603 std::swap(LHSCC, RHSCC);
3604 }
3605
3606 // At this point, we know we have have two setcc instructions
3607 // comparing a value against two constants and or'ing the result
3608 // together. Because of the above check, we know that we only have
3609 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3610 // FoldSetCCLogical check above), that the two constants are not
3611 // equal.
3612 assert(LHSCst != RHSCst && "Compares not folded above?");
3613
3614 switch (LHSCC) {
3615 default: assert(0 && "Unknown integer condition code!");
3616 case Instruction::SetEQ:
3617 switch (RHSCC) {
3618 default: assert(0 && "Unknown integer condition code!");
3619 case Instruction::SetEQ:
3620 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3621 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3622 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3623 LHSVal->getName()+".off");
3624 InsertNewInstBefore(Add, I);
3625 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003626 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3627 UnsType, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003628 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003629 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003630 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3631 }
3632 break; // (X == 13 | X == 15) -> no change
3633
Chris Lattner5c219462005-04-19 06:04:18 +00003634 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3635 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003636 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3637 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3638 return ReplaceInstUsesWith(I, RHS);
3639 }
3640 break;
3641 case Instruction::SetNE:
3642 switch (RHSCC) {
3643 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003644 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3645 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3646 return ReplaceInstUsesWith(I, LHS);
3647 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003648 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003649 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003650 }
3651 break;
3652 case Instruction::SetLT:
3653 switch (RHSCC) {
3654 default: assert(0 && "Unknown integer condition code!");
3655 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3656 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003657 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3658 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003659 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3660 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3661 return ReplaceInstUsesWith(I, RHS);
3662 }
3663 break;
3664 case Instruction::SetGT:
3665 switch (RHSCC) {
3666 default: assert(0 && "Unknown integer condition code!");
3667 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3668 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3669 return ReplaceInstUsesWith(I, LHS);
3670 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3671 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003672 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003673 }
3674 }
3675 }
3676 }
Chris Lattner3af10532006-05-05 06:39:07 +00003677
3678 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003679 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003680 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003681 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3682 const Type *SrcTy = Op0C->getOperand(0)->getType();
3683 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3684 // Only do this if the casts both really cause code to be generated.
3685 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3686 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3687 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3688 Op1C->getOperand(0),
3689 I.getName());
3690 InsertNewInstBefore(NewOp, I);
3691 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3692 }
Chris Lattner3af10532006-05-05 06:39:07 +00003693 }
Chris Lattner3af10532006-05-05 06:39:07 +00003694
Chris Lattner15212982005-09-18 03:42:07 +00003695
Chris Lattner113f4f42002-06-25 16:13:24 +00003696 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003697}
3698
Chris Lattnerc2076352004-02-16 01:20:27 +00003699// XorSelf - Implements: X ^ X --> 0
3700struct XorSelf {
3701 Value *RHS;
3702 XorSelf(Value *rhs) : RHS(rhs) {}
3703 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3704 Instruction *apply(BinaryOperator &Xor) const {
3705 return &Xor;
3706 }
3707};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003708
3709
Chris Lattner113f4f42002-06-25 16:13:24 +00003710Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003711 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003712 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003713
Chris Lattner81a7a232004-10-16 18:11:37 +00003714 if (isa<UndefValue>(Op1))
3715 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3716
Chris Lattnerc2076352004-02-16 01:20:27 +00003717 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3718 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3719 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003720 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003721 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003722
3723 // See if we can simplify any instructions used by the instruction whose sole
3724 // purpose is to compute bits we don't care about.
3725 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003726 if (!isa<PackedType>(I.getType()) &&
3727 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003728 KnownZero, KnownOne))
3729 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003730
Chris Lattner97638592003-07-23 21:37:07 +00003731 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003732 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003733 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003734 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003735 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003736 return new SetCondInst(SCI->getInverseCondition(),
3737 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003738
Chris Lattner8f2f5982003-11-05 01:06:05 +00003739 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003740 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3741 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003742 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3743 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003744 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003745 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003746 }
Chris Lattner023a4832004-06-18 06:07:51 +00003747
3748 // ~(~X & Y) --> (X | ~Y)
3749 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3750 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3751 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3752 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003753 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003754 Op0I->getOperand(1)->getName()+".not");
3755 InsertNewInstBefore(NotY, I);
3756 return BinaryOperator::createOr(Op0NotVal, NotY);
3757 }
3758 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003759
Chris Lattner97638592003-07-23 21:37:07 +00003760 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003761 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003762 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003763 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003764 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3765 return BinaryOperator::createSub(
3766 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003767 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003768 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003769 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003770 } else if (Op0I->getOpcode() == Instruction::Or) {
3771 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3772 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3773 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3774 // Anything in both C1 and C2 is known to be zero, remove it from
3775 // NewRHS.
3776 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3777 NewRHS = ConstantExpr::getAnd(NewRHS,
3778 ConstantExpr::getNot(CommonBits));
3779 WorkList.push_back(Op0I);
3780 I.setOperand(0, Op0I->getOperand(0));
3781 I.setOperand(1, NewRHS);
3782 return &I;
3783 }
Chris Lattner97638592003-07-23 21:37:07 +00003784 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003785 }
Chris Lattner183b3362004-04-09 19:05:30 +00003786
3787 // Try to fold constant and into select arguments.
3788 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003789 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003790 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003791 if (isa<PHINode>(Op0))
3792 if (Instruction *NV = FoldOpIntoPhi(I))
3793 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003794 }
3795
Chris Lattnerbb74e222003-03-10 23:06:50 +00003796 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003797 if (X == Op1)
3798 return ReplaceInstUsesWith(I,
3799 ConstantIntegral::getAllOnesValue(I.getType()));
3800
Chris Lattnerbb74e222003-03-10 23:06:50 +00003801 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003802 if (X == Op0)
3803 return ReplaceInstUsesWith(I,
3804 ConstantIntegral::getAllOnesValue(I.getType()));
3805
Chris Lattnerdcd07922006-04-01 08:03:55 +00003806 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003807 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003808 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003809 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003810 I.swapOperands();
3811 std::swap(Op0, Op1);
3812 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003813 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003814 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003815 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003816 } else if (Op1I->getOpcode() == Instruction::Xor) {
3817 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3818 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3819 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3820 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003821 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3822 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3823 Op1I->swapOperands();
3824 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3825 I.swapOperands(); // Simplified below.
3826 std::swap(Op0, Op1);
3827 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003828 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003829
Chris Lattnerdcd07922006-04-01 08:03:55 +00003830 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003831 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003832 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003833 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003834 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003835 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3836 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003837 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003838 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003839 } else if (Op0I->getOpcode() == Instruction::Xor) {
3840 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3841 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3842 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3843 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003844 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3845 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3846 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003847 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3848 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003849 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3850 InsertNewInstBefore(N, I);
3851 return BinaryOperator::createAnd(N, Op1);
3852 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003853 }
3854
Chris Lattner3ac7c262003-08-13 20:16:26 +00003855 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3856 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3857 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3858 return R;
3859
Chris Lattner3af10532006-05-05 06:39:07 +00003860 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003861 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003862 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003863 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3864 const Type *SrcTy = Op0C->getOperand(0)->getType();
3865 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3866 // Only do this if the casts both really cause code to be generated.
3867 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3868 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3869 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3870 Op1C->getOperand(0),
3871 I.getName());
3872 InsertNewInstBefore(NewOp, I);
3873 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3874 }
Chris Lattner3af10532006-05-05 06:39:07 +00003875 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003876
3877 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3878 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3879 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3880 if (SI0->getOpcode() == SI1->getOpcode() &&
3881 SI0->getOperand(1) == SI1->getOperand(1) &&
3882 (SI0->hasOneUse() || SI1->hasOneUse())) {
3883 Instruction *NewOp =
3884 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3885 SI1->getOperand(0),
3886 SI0->getName()), I);
3887 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3888 }
3889 }
Chris Lattner3af10532006-05-05 06:39:07 +00003890
Chris Lattner113f4f42002-06-25 16:13:24 +00003891 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003892}
3893
Chris Lattner6862fbd2004-09-29 17:40:11 +00003894static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003895 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003896}
3897
3898/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3899/// overflowed for this type.
3900static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3901 ConstantInt *In2) {
3902 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3903
3904 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003905 return cast<ConstantInt>(Result)->getZExtValue() <
3906 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003907 if (isPositive(In1) != isPositive(In2))
3908 return false;
3909 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003910 return cast<ConstantInt>(Result)->getSExtValue() <
3911 cast<ConstantInt>(In1)->getSExtValue();
3912 return cast<ConstantInt>(Result)->getSExtValue() >
3913 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003914}
3915
Chris Lattner0798af32005-01-13 20:14:25 +00003916/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3917/// code necessary to compute the offset from the base pointer (without adding
3918/// in the base pointer). Return the result as a signed integer of intptr size.
3919static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3920 TargetData &TD = IC.getTargetData();
3921 gep_type_iterator GTI = gep_type_begin(GEP);
3922 const Type *UIntPtrTy = TD.getIntPtrType();
3923 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3924 Value *Result = Constant::getNullValue(SIntPtrTy);
3925
3926 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003927 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003928
Chris Lattner0798af32005-01-13 20:14:25 +00003929 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3930 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003931 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer13bc5d72006-12-12 09:18:51 +00003932 Constant *Scale = ConstantExpr::getBitCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003933 SIntPtrTy);
3934 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3935 if (!OpC->isNullValue()) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00003936 OpC = ConstantExpr::getIntegerCast(OpC, SIntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00003937 Scale = ConstantExpr::getMul(OpC, Scale);
3938 if (Constant *RC = dyn_cast<Constant>(Result))
3939 Result = ConstantExpr::getAdd(RC, Scale);
3940 else {
3941 // Emit an add instruction.
3942 Result = IC.InsertNewInstBefore(
3943 BinaryOperator::createAdd(Result, Scale,
3944 GEP->getName()+".offs"), I);
3945 }
3946 }
3947 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003948 // Convert to correct type.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003949 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, SIntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003950 Op->getName()+".c"), I);
3951 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003952 // We'll let instcombine(mul) convert this to a shl if possible.
3953 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3954 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003955
3956 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003957 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003958 GEP->getName()+".offs"), I);
3959 }
3960 }
3961 return Result;
3962}
3963
3964/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3965/// else. At this point we know that the GEP is on the LHS of the comparison.
3966Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3967 Instruction::BinaryOps Cond,
3968 Instruction &I) {
3969 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003970
3971 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3972 if (isa<PointerType>(CI->getOperand(0)->getType()))
3973 RHS = CI->getOperand(0);
3974
Chris Lattner0798af32005-01-13 20:14:25 +00003975 Value *PtrBase = GEPLHS->getOperand(0);
3976 if (PtrBase == RHS) {
3977 // As an optimization, we don't actually have to compute the actual value of
3978 // OFFSET if this is a seteq or setne comparison, just return whether each
3979 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003980 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3981 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003982 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3983 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003984 bool EmitIt = true;
3985 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3986 if (isa<UndefValue>(C)) // undef index -> undef.
3987 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3988 if (C->isNullValue())
3989 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003990 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3991 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003992 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003993 return ReplaceInstUsesWith(I, // No comparison is needed here.
3994 ConstantBool::get(Cond == Instruction::SetNE));
3995 }
3996
3997 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003998 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003999 new SetCondInst(Cond, GEPLHS->getOperand(i),
4000 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4001 if (InVal == 0)
4002 InVal = Comp;
4003 else {
4004 InVal = InsertNewInstBefore(InVal, I);
4005 InsertNewInstBefore(Comp, I);
4006 if (Cond == Instruction::SetNE) // True if any are unequal
4007 InVal = BinaryOperator::createOr(InVal, Comp);
4008 else // True if all are equal
4009 InVal = BinaryOperator::createAnd(InVal, Comp);
4010 }
4011 }
4012 }
4013
4014 if (InVal)
4015 return InVal;
4016 else
4017 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4018 ConstantBool::get(Cond == Instruction::SetEQ));
4019 }
Chris Lattner0798af32005-01-13 20:14:25 +00004020
4021 // Only lower this if the setcc is the only user of the GEP or if we expect
4022 // the result to fold to a constant!
4023 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4024 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4025 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4026 return new SetCondInst(Cond, Offset,
4027 Constant::getNullValue(Offset->getType()));
4028 }
4029 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004030 // If the base pointers are different, but the indices are the same, just
4031 // compare the base pointer.
4032 if (PtrBase != GEPRHS->getOperand(0)) {
4033 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004034 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004035 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004036 if (IndicesTheSame)
4037 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4038 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4039 IndicesTheSame = false;
4040 break;
4041 }
4042
4043 // If all indices are the same, just compare the base pointers.
4044 if (IndicesTheSame)
4045 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4046 GEPRHS->getOperand(0));
4047
4048 // Otherwise, the base pointers are different and the indices are
4049 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004050 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004051 }
Chris Lattner0798af32005-01-13 20:14:25 +00004052
Chris Lattner81e84172005-01-13 22:25:21 +00004053 // If one of the GEPs has all zero indices, recurse.
4054 bool AllZeros = true;
4055 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4056 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4057 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4058 AllZeros = false;
4059 break;
4060 }
4061 if (AllZeros)
4062 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4063 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004064
4065 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004066 AllZeros = true;
4067 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4068 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4069 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4070 AllZeros = false;
4071 break;
4072 }
4073 if (AllZeros)
4074 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4075
Chris Lattner4fa89822005-01-14 00:20:05 +00004076 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4077 // If the GEPs only differ by one index, compare it.
4078 unsigned NumDifferences = 0; // Keep track of # differences.
4079 unsigned DiffOperand = 0; // The operand that differs.
4080 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4081 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004082 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4083 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004084 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004085 NumDifferences = 2;
4086 break;
4087 } else {
4088 if (NumDifferences++) break;
4089 DiffOperand = i;
4090 }
4091 }
4092
4093 if (NumDifferences == 0) // SAME GEP?
4094 return ReplaceInstUsesWith(I, // No comparison is needed here.
4095 ConstantBool::get(Cond == Instruction::SetEQ));
4096 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004097 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4098 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004099
4100 // Convert the operands to signed values to make sure to perform a
4101 // signed comparison.
4102 const Type *NewTy = LHSV->getType()->getSignedVersion();
4103 if (LHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004104 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004105 if (RHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004106 RHSV = InsertCastBefore(Instruction::BitCast, RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004107 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004108 }
4109 }
4110
Chris Lattner0798af32005-01-13 20:14:25 +00004111 // Only lower this if the setcc is the only user of the GEP or if we expect
4112 // the result to fold to a constant!
4113 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4114 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4115 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4116 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4117 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4118 return new SetCondInst(Cond, L, R);
4119 }
4120 }
4121 return 0;
4122}
4123
4124
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004125Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004126 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004127 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4128 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004129
4130 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004131 if (Op0 == Op1)
4132 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004133
Chris Lattner81a7a232004-10-16 18:11:37 +00004134 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4135 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4136
Chris Lattner15ff1e12004-11-14 07:33:16 +00004137 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4138 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004139 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4140 isa<ConstantPointerNull>(Op0)) &&
4141 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004142 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004143 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4144
4145 // setcc's with boolean values can always be turned into bitwise operations
4146 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004147 switch (I.getOpcode()) {
4148 default: assert(0 && "Invalid setcc instruction!");
4149 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004150 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004151 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004152 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004153 }
Chris Lattner4456da62004-08-11 00:50:51 +00004154 case Instruction::SetNE:
4155 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004156
Chris Lattner4456da62004-08-11 00:50:51 +00004157 case Instruction::SetGT:
4158 std::swap(Op0, Op1); // Change setgt -> setlt
4159 // FALL THROUGH
4160 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4161 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4162 InsertNewInstBefore(Not, I);
4163 return BinaryOperator::createAnd(Not, Op1);
4164 }
4165 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004166 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004167 // FALL THROUGH
4168 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4169 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4170 InsertNewInstBefore(Not, I);
4171 return BinaryOperator::createOr(Not, Op1);
4172 }
4173 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004174 }
4175
Chris Lattner2dd01742004-06-09 04:24:29 +00004176 // See if we are doing a comparison between a constant and an instruction that
4177 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004178 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004179 // Check to see if we are comparing against the minimum or maximum value...
Reid Spencer4ae56f32006-12-06 20:39:57 +00004180 if (CI->isMinValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004181 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004182 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004183 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004184 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004185 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4186 return BinaryOperator::createSetEQ(Op0, Op1);
4187 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4188 return BinaryOperator::createSetNE(Op0, Op1);
4189
Reid Spencer4ae56f32006-12-06 20:39:57 +00004190 } else if (CI->isMaxValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004191 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004192 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004193 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004194 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004195 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4196 return BinaryOperator::createSetEQ(Op0, Op1);
4197 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4198 return BinaryOperator::createSetNE(Op0, Op1);
4199
4200 // Comparing against a value really close to min or max?
4201 } else if (isMinValuePlusOne(CI)) {
4202 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4203 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4204 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4205 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4206
4207 } else if (isMaxValueMinusOne(CI)) {
4208 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4209 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4210 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4211 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4212 }
4213
4214 // If we still have a setle or setge instruction, turn it into the
4215 // appropriate setlt or setgt instruction. Since the border cases have
4216 // already been handled above, this requires little checking.
4217 //
4218 if (I.getOpcode() == Instruction::SetLE)
4219 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4220 if (I.getOpcode() == Instruction::SetGE)
4221 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4222
Chris Lattneree0f2802006-02-12 02:07:56 +00004223
4224 // See if we can fold the comparison based on bits known to be zero or one
4225 // in the input.
4226 uint64_t KnownZero, KnownOne;
4227 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4228 KnownZero, KnownOne, 0))
4229 return &I;
4230
4231 // Given the known and unknown bits, compute a range that the LHS could be
4232 // in.
4233 if (KnownOne | KnownZero) {
4234 if (Ty->isUnsigned()) { // Unsigned comparison.
4235 uint64_t Min, Max;
4236 uint64_t RHSVal = CI->getZExtValue();
4237 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4238 Min, Max);
4239 switch (I.getOpcode()) { // LE/GE have been folded already.
4240 default: assert(0 && "Unknown setcc opcode!");
4241 case Instruction::SetEQ:
4242 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004243 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004244 break;
4245 case Instruction::SetNE:
4246 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004247 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004248 break;
4249 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004250 if (Max < RHSVal)
4251 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4252 if (Min > RHSVal)
4253 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004254 break;
4255 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004256 if (Min > RHSVal)
4257 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4258 if (Max < RHSVal)
4259 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004260 break;
4261 }
4262 } else { // Signed comparison.
4263 int64_t Min, Max;
4264 int64_t RHSVal = CI->getSExtValue();
4265 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4266 Min, Max);
4267 switch (I.getOpcode()) { // LE/GE have been folded already.
4268 default: assert(0 && "Unknown setcc opcode!");
4269 case Instruction::SetEQ:
4270 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004271 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004272 break;
4273 case Instruction::SetNE:
4274 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004275 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004276 break;
4277 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004278 if (Max < RHSVal)
4279 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4280 if (Min > RHSVal)
4281 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004282 break;
4283 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004284 if (Min > RHSVal)
4285 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4286 if (Max < RHSVal)
4287 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004288 break;
4289 }
4290 }
4291 }
4292
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004293 // Since the RHS is a constantInt (CI), if the left hand side is an
4294 // instruction, see if that instruction also has constants so that the
4295 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004296 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004297 switch (LHSI->getOpcode()) {
4298 case Instruction::And:
4299 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4300 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004301 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4302
4303 // If an operand is an AND of a truncating cast, we can widen the
4304 // and/compare to be the input width without changing the value
4305 // produced, eliminating a cast.
4306 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4307 // We can do this transformation if either the AND constant does not
4308 // have its sign bit set or if it is an equality comparison.
4309 // Extending a relational comparison when we're checking the sign
4310 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004311 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004312 (I.isEquality() ||
4313 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4314 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4315 ConstantInt *NewCST;
4316 ConstantInt *NewCI;
4317 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004318 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004319 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004320 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004321 CI->getZExtValue());
4322 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004323 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004324 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004325 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004326 CI->getZExtValue());
4327 }
4328 Instruction *NewAnd =
4329 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4330 LHSI->getName());
4331 InsertNewInstBefore(NewAnd, I);
4332 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4333 }
4334 }
4335
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004336 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4337 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4338 // happens a LOT in code produced by the C front-end, for bitfield
4339 // access.
4340 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004341
4342 // Check to see if there is a noop-cast between the shift and the and.
4343 if (!Shift) {
4344 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4345 if (CI->getOperand(0)->getType()->isIntegral() &&
4346 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4347 CI->getType()->getPrimitiveSizeInBits())
4348 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4349 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004350
Reid Spencere0fc4df2006-10-20 07:07:24 +00004351 ConstantInt *ShAmt;
4352 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004353 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4354 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004355
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004356 // We can fold this as long as we can't shift unknown bits
4357 // into the mask. This can only happen with signed shift
4358 // rights, as they sign-extend.
4359 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004360 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004361 if (!CanFold) {
4362 // To test for the bad case of the signed shr, see if any
4363 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004364 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004365 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4366
Reid Spencere0fc4df2006-10-20 07:07:24 +00004367 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004368 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004369 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4370 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004371 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4372 CanFold = true;
4373 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004374
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004375 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004376 Constant *NewCst;
4377 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004378 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004379 else
4380 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004381
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004382 // Check to see if we are shifting out any of the bits being
4383 // compared.
4384 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4385 // If we shifted bits out, the fold is not going to work out.
4386 // As a special case, check to see if this means that the
4387 // result is always true or false now.
4388 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004389 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004390 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004391 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004392 } else {
4393 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004394 Constant *NewAndCST;
4395 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004396 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004397 else
4398 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4399 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004400 if (AndTy == Ty)
4401 LHSI->setOperand(0, Shift->getOperand(0));
4402 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004403 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4404 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004405 *Shift);
4406 LHSI->setOperand(0, NewCast);
4407 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004408 WorkList.push_back(Shift); // Shift is dead.
4409 AddUsesToWorkList(I);
4410 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004411 }
4412 }
Chris Lattner35167c32004-06-09 07:59:58 +00004413 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004414
4415 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4416 // preferable because it allows the C<<Y expression to be hoisted out
4417 // of a loop if Y is invariant and X is not.
4418 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004419 I.isEquality() && !Shift->isArithmeticShift() &&
4420 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004421 // Compute C << Y.
4422 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004423 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004424 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4425 "tmp");
4426 } else {
4427 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004428 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004429 if (AndCST->getType()->isSigned())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004430 NewAndCST = ConstantExpr::getBitCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004431 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004432 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004433 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004434 }
4435 InsertNewInstBefore(cast<Instruction>(NS), I);
4436
4437 // If C's sign doesn't agree with the and, insert a cast now.
4438 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004439 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4440 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004441
4442 Value *ShiftOp = Shift->getOperand(0);
4443 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004444 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4445 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004446
4447 // Compute X & (C << Y).
4448 Instruction *NewAnd =
4449 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4450 InsertNewInstBefore(NewAnd, I);
4451
4452 I.setOperand(0, NewAnd);
4453 return &I;
4454 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004455 }
4456 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004457
Chris Lattner272d5ca2004-09-28 18:22:15 +00004458 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004459 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004460 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004461 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4462
4463 // Check that the shift amount is in range. If not, don't perform
4464 // undefined shifts. When the shift is visited it will be
4465 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004466 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004467 break;
4468
Chris Lattner272d5ca2004-09-28 18:22:15 +00004469 // If we are comparing against bits always shifted out, the
4470 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004471 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004472 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004473 if (Comp != CI) {// Comparing against a bit that we know is zero.
4474 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4475 Constant *Cst = ConstantBool::get(IsSetNE);
4476 return ReplaceInstUsesWith(I, Cst);
4477 }
4478
4479 if (LHSI->hasOneUse()) {
4480 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004481 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004482 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4483
4484 Constant *Mask;
4485 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004486 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004487 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004488 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004489 } else {
4490 Mask = ConstantInt::getAllOnesValue(CI->getType());
4491 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004492
Chris Lattner272d5ca2004-09-28 18:22:15 +00004493 Instruction *AndI =
4494 BinaryOperator::createAnd(LHSI->getOperand(0),
4495 Mask, LHSI->getName()+".mask");
4496 Value *And = InsertNewInstBefore(AndI, I);
4497 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004498 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004499 }
4500 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004501 }
4502 break;
4503
Reid Spencerfdff9382006-11-08 06:47:33 +00004504 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4505 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004506 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004507 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004508 // Check that the shift amount is in range. If not, don't perform
4509 // undefined shifts. When the shift is visited it will be
4510 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004511 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004512 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004513 break;
4514
Chris Lattner1023b872004-09-27 16:18:50 +00004515 // If we are comparing against bits always shifted out, the
4516 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004517 Constant *Comp;
4518 if (CI->getType()->isUnsigned())
4519 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4520 ShAmt);
4521 else
4522 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4523 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004524
Chris Lattner1023b872004-09-27 16:18:50 +00004525 if (Comp != CI) {// Comparing against a bit that we know is zero.
4526 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4527 Constant *Cst = ConstantBool::get(IsSetNE);
4528 return ReplaceInstUsesWith(I, Cst);
4529 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004530
Chris Lattner1023b872004-09-27 16:18:50 +00004531 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004532 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004533
Chris Lattner1023b872004-09-27 16:18:50 +00004534 // Otherwise strength reduce the shift into an and.
4535 uint64_t Val = ~0ULL; // All ones.
4536 Val <<= ShAmtVal; // Shift over to the right spot.
4537
4538 Constant *Mask;
4539 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004540 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004541 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004542 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004543 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004544 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004545
Chris Lattner1023b872004-09-27 16:18:50 +00004546 Instruction *AndI =
4547 BinaryOperator::createAnd(LHSI->getOperand(0),
4548 Mask, LHSI->getName()+".mask");
4549 Value *And = InsertNewInstBefore(AndI, I);
4550 return new SetCondInst(I.getOpcode(), And,
4551 ConstantExpr::getShl(CI, ShAmt));
4552 }
Chris Lattner1023b872004-09-27 16:18:50 +00004553 }
4554 }
4555 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004556
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004557 case Instruction::SDiv:
4558 case Instruction::UDiv:
4559 // Fold: setcc ([us]div X, C1), C2 -> range test
4560 // Fold this div into the comparison, producing a range check.
4561 // Determine, based on the divide type, what the range is being
4562 // checked. If there is an overflow on the low or high side, remember
4563 // it, otherwise compute the range [low, hi) bounding the new value.
4564 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004565 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004566 // FIXME: If the operand types don't match the type of the divide
4567 // then don't attempt this transform. The code below doesn't have the
4568 // logic to deal with a signed divide and an unsigned compare (and
4569 // vice versa). This is because (x /s C1) <s C2 produces different
4570 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4571 // (x /u C1) <u C2. Simply casting the operands and result won't
4572 // work. :( The if statement below tests that condition and bails
4573 // if it finds it.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004574 const Type *DivRHSTy = DivRHS->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004575 unsigned DivOpCode = LHSI->getOpcode();
4576 if (I.isEquality() &&
4577 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4578 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4579 break;
4580
4581 // Initialize the variables that will indicate the nature of the
4582 // range check.
4583 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004584 ConstantInt *LoBound = 0, *HiBound = 0;
4585
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004586 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4587 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4588 // C2 (CI). By solving for X we can turn this into a range check
4589 // instead of computing a divide.
4590 ConstantInt *Prod =
4591 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004592
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004593 // Determine if the product overflows by seeing if the product is
4594 // not equal to the divide. Make sure we do the same kind of divide
4595 // as in the LHS instruction that we're folding.
4596 bool ProdOV = !DivRHS->isNullValue() &&
4597 (DivOpCode == Instruction::SDiv ?
4598 ConstantExpr::getSDiv(Prod, DivRHS) :
4599 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4600
4601 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004602 Instruction::BinaryOps Opcode = I.getOpcode();
4603
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004604 if (DivRHS->isNullValue()) {
4605 // Don't hack on divide by zeros!
4606 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004607 LoBound = Prod;
4608 LoOverflow = ProdOV;
4609 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004610 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004611 if (CI->isNullValue()) { // (X / pos) op 0
4612 // Can't overflow.
4613 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4614 HiBound = DivRHS;
4615 } else if (isPositive(CI)) { // (X / pos) op pos
4616 LoBound = Prod;
4617 LoOverflow = ProdOV;
4618 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4619 } else { // (X / pos) op neg
4620 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4621 LoOverflow = AddWithOverflow(LoBound, Prod,
4622 cast<ConstantInt>(DivRHSH));
4623 HiBound = Prod;
4624 HiOverflow = ProdOV;
4625 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004626 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004627 if (CI->isNullValue()) { // (X / neg) op 0
4628 LoBound = AddOne(DivRHS);
4629 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004630 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004631 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004632 } else if (isPositive(CI)) { // (X / neg) op pos
4633 HiOverflow = LoOverflow = ProdOV;
4634 if (!LoOverflow)
4635 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4636 HiBound = AddOne(Prod);
4637 } else { // (X / neg) op neg
4638 LoBound = Prod;
4639 LoOverflow = HiOverflow = ProdOV;
4640 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4641 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004642
Chris Lattnera92af962004-10-11 19:40:04 +00004643 // Dividing by a negate swaps the condition.
4644 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004645 }
4646
4647 if (LoBound) {
4648 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004649 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004650 default: assert(0 && "Unhandled setcc opcode!");
4651 case Instruction::SetEQ:
4652 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004653 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004654 else if (HiOverflow)
4655 return new SetCondInst(Instruction::SetGE, X, LoBound);
4656 else if (LoOverflow)
4657 return new SetCondInst(Instruction::SetLT, X, HiBound);
4658 else
4659 return InsertRangeTest(X, LoBound, HiBound, true, I);
4660 case Instruction::SetNE:
4661 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004662 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004663 else if (HiOverflow)
4664 return new SetCondInst(Instruction::SetLT, X, LoBound);
4665 else if (LoOverflow)
4666 return new SetCondInst(Instruction::SetGE, X, HiBound);
4667 else
4668 return InsertRangeTest(X, LoBound, HiBound, false, I);
4669 case Instruction::SetLT:
4670 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004671 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004672 return new SetCondInst(Instruction::SetLT, X, LoBound);
4673 case Instruction::SetGT:
4674 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004675 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004676 return new SetCondInst(Instruction::SetGE, X, HiBound);
4677 }
4678 }
4679 }
4680 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004681 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004682
Chris Lattnera7942b72006-11-29 05:02:16 +00004683 // Simplify seteq and setne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004684 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004685 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4686
Reid Spencere0fc4df2006-10-20 07:07:24 +00004687 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4688 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004689 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4690 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004691 case Instruction::SRem:
4692 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4693 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4694 BO->hasOneUse()) {
4695 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4696 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004697 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4698 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004699 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004700 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004701 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004702 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004703 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004704 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004705 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4706 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004707 if (BO->hasOneUse())
4708 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4709 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004710 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004711 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4712 // efficiently invertible, or if the add has just this one use.
4713 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004714
Chris Lattnerc992add2003-08-13 05:33:12 +00004715 if (Value *NegVal = dyn_castNegVal(BOp1))
4716 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4717 else if (Value *NegVal = dyn_castNegVal(BOp0))
4718 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004719 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004720 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4721 BO->setName("");
4722 InsertNewInstBefore(Neg, I);
4723 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4724 }
4725 }
4726 break;
4727 case Instruction::Xor:
4728 // For the xor case, we can xor two constants together, eliminating
4729 // the explicit xor.
4730 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4731 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004732 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004733
4734 // FALLTHROUGH
4735 case Instruction::Sub:
4736 // Replace (([sub|xor] A, B) != 0) with (A != B)
4737 if (CI->isNullValue())
4738 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4739 BO->getOperand(1));
4740 break;
4741
4742 case Instruction::Or:
4743 // If bits are being or'd in that are not present in the constant we
4744 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004745 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004746 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004747 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004748 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004749 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004750 break;
4751
4752 case Instruction::And:
4753 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004754 // If bits are being compared against that are and'd out, then the
4755 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004756 if (!ConstantExpr::getAnd(CI,
4757 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004758 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004759
Chris Lattner35167c32004-06-09 07:59:58 +00004760 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004761 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004762 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4763 Instruction::SetNE, Op0,
4764 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004765
Chris Lattnerc992add2003-08-13 05:33:12 +00004766 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4767 // to be a signed value as appropriate.
4768 if (isSignBit(BOC)) {
4769 Value *X = BO->getOperand(0);
4770 // If 'X' is not signed, insert a cast now...
4771 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004772 const Type *DestTy = BOC->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004773 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004774 }
4775 return new SetCondInst(isSetNE ? Instruction::SetLT :
4776 Instruction::SetGE, X,
4777 Constant::getNullValue(X->getType()));
4778 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004779
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004780 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004781 if (CI->isNullValue() && isHighOnes(BOC)) {
4782 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004783 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004784
4785 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004786 if (NegX->getType()->isSigned()) {
4787 const Type *DestTy = NegX->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004788 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
4789 NegX = ConstantExpr::getBitCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004790 }
4791
4792 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004793 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004794 }
4795
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004796 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004797 default: break;
4798 }
Chris Lattnera7942b72006-11-29 05:02:16 +00004799 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4800 // Handle set{eq|ne} <intrinsic>, intcst.
4801 switch (II->getIntrinsicID()) {
4802 default: break;
4803 case Intrinsic::bswap_i16: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4804 WorkList.push_back(II); // Dead?
4805 I.setOperand(0, II->getOperand(1));
4806 I.setOperand(1, ConstantInt::get(Type::UShortTy,
4807 ByteSwap_16(CI->getZExtValue())));
4808 return &I;
4809 case Intrinsic::bswap_i32: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4810 WorkList.push_back(II); // Dead?
4811 I.setOperand(0, II->getOperand(1));
4812 I.setOperand(1, ConstantInt::get(Type::UIntTy,
4813 ByteSwap_32(CI->getZExtValue())));
4814 return &I;
4815 case Intrinsic::bswap_i64: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4816 WorkList.push_back(II); // Dead?
4817 I.setOperand(0, II->getOperand(1));
4818 I.setOperand(1, ConstantInt::get(Type::ULongTy,
4819 ByteSwap_64(CI->getZExtValue())));
4820 return &I;
4821 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004822 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004823 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004824 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004825 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4826 Value *CastOp = Cast->getOperand(0);
4827 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004828 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004829 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004830 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004831 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004832 "Source and destination signednesses should differ!");
4833 if (Cast->getType()->isSigned()) {
4834 // If this is a signed comparison, check for comparisons in the
4835 // vicinity of zero.
4836 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4837 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004838 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004839 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004840 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004841 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004842 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004843 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004844 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004845 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004846 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004847 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004848 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004849 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004850 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004851 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004852 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004853 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004854 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004855 return BinaryOperator::createSetLT(CastOp,
4856 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004857 }
4858 }
4859 }
Chris Lattnere967b342003-06-04 05:10:11 +00004860 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004861 }
4862
Chris Lattner77c32c32005-04-23 15:31:55 +00004863 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4864 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4865 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4866 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004867 case Instruction::GetElementPtr:
4868 if (RHSC->isNullValue()) {
4869 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4870 bool isAllZeros = true;
4871 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4872 if (!isa<Constant>(LHSI->getOperand(i)) ||
4873 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4874 isAllZeros = false;
4875 break;
4876 }
4877 if (isAllZeros)
4878 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4879 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4880 }
4881 break;
4882
Chris Lattner77c32c32005-04-23 15:31:55 +00004883 case Instruction::PHI:
4884 if (Instruction *NV = FoldOpIntoPhi(I))
4885 return NV;
4886 break;
4887 case Instruction::Select:
4888 // If either operand of the select is a constant, we can fold the
4889 // comparison into the select arms, which will cause one to be
4890 // constant folded and the select turned into a bitwise or.
4891 Value *Op1 = 0, *Op2 = 0;
4892 if (LHSI->hasOneUse()) {
4893 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4894 // Fold the known value into the constant operand.
4895 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4896 // Insert a new SetCC of the other select operand.
4897 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4898 LHSI->getOperand(2), RHSC,
4899 I.getName()), I);
4900 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4901 // Fold the known value into the constant operand.
4902 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4903 // Insert a new SetCC of the other select operand.
4904 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4905 LHSI->getOperand(1), RHSC,
4906 I.getName()), I);
4907 }
4908 }
Jeff Cohen82639852005-04-23 21:38:35 +00004909
Chris Lattner77c32c32005-04-23 15:31:55 +00004910 if (Op1)
4911 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4912 break;
4913 }
4914 }
4915
Chris Lattner0798af32005-01-13 20:14:25 +00004916 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4917 if (User *GEP = dyn_castGetElementPtr(Op0))
4918 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4919 return NI;
4920 if (User *GEP = dyn_castGetElementPtr(Op1))
4921 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4922 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4923 return NI;
4924
Chris Lattner16930792003-11-03 04:25:02 +00004925 // Test to see if the operands of the setcc are casted versions of other
4926 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004927 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4928 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004929 if (CI->isLosslessCast() && I.isEquality() &&
4930 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004931 // We keep moving the cast from the left operand over to the right
4932 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004933 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004934
Chris Lattner16930792003-11-03 04:25:02 +00004935 // If operand #1 is a cast instruction, see if we can eliminate it as
4936 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004937 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4938 Value *CI2Op0 = CI2->getOperand(0);
4939 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4940 Op1 = CI2Op0;
4941 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004942
Chris Lattner16930792003-11-03 04:25:02 +00004943 // If Op1 is a constant, we can fold the cast into the constant.
4944 if (Op1->getType() != Op0->getType())
4945 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004946 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004947 } else {
4948 // Otherwise, cast the RHS right before the setcc
Reid Spencer13bc5d72006-12-12 09:18:51 +00004949 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004950 }
4951 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4952 }
4953
Chris Lattner6444c372003-11-03 05:17:03 +00004954 // Handle the special case of: setcc (cast bool to X), <cst>
4955 // This comes up when you have code like
4956 // int X = A < B;
4957 // if (X) ...
4958 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004959 // with a constant or another cast from the same type.
4960 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4961 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4962 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004963 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004964
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004965 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004966 Value *A, *B;
4967 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4968 (A == Op1 || B == Op1)) {
4969 // (A^B) == A -> B == 0
4970 Value *OtherVal = A == Op1 ? B : A;
4971 return BinaryOperator::create(I.getOpcode(), OtherVal,
4972 Constant::getNullValue(A->getType()));
4973 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4974 (A == Op0 || B == Op0)) {
4975 // A == (A^B) -> B == 0
4976 Value *OtherVal = A == Op0 ? B : A;
4977 return BinaryOperator::create(I.getOpcode(), OtherVal,
4978 Constant::getNullValue(A->getType()));
4979 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4980 // (A-B) == A -> B == 0
4981 return BinaryOperator::create(I.getOpcode(), B,
4982 Constant::getNullValue(B->getType()));
4983 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4984 // A == (A-B) -> B == 0
4985 return BinaryOperator::create(I.getOpcode(), B,
4986 Constant::getNullValue(B->getType()));
4987 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004988
4989 Value *C, *D;
4990 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4991 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4992 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4993 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4994 Value *X = 0, *Y = 0, *Z = 0;
4995
4996 if (A == C) {
4997 X = B; Y = D; Z = A;
4998 } else if (A == D) {
4999 X = B; Y = C; Z = A;
5000 } else if (B == C) {
5001 X = A; Y = D; Z = B;
5002 } else if (B == D) {
5003 X = A; Y = C; Z = B;
5004 }
5005
5006 if (X) { // Build (X^Y) & Z
5007 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5008 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5009 I.setOperand(0, Op1);
5010 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5011 return &I;
5012 }
5013 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005014 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005015 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005016}
5017
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005018// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5019// We only handle extending casts so far.
5020//
5021Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005022 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5023 Value *LHSCIOp = LHSCI->getOperand(0);
5024 const Type *SrcTy = LHSCIOp->getType();
5025 const Type *DestTy = SCI.getOperand(0)->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005026 Value *RHSCIOp;
5027
5028 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00005029 return 0;
5030
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005031 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5032 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5033 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5034
5035 // Is this a sign or zero extension?
5036 bool isSignSrc = SrcTy->isSigned();
5037 bool isSignDest = DestTy->isSigned();
5038
5039 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5040 // Not an extension from the same type?
5041 RHSCIOp = CI->getOperand(0);
5042 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5043 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5044 // Compute the constant that would happen if we truncated to SrcTy then
5045 // reextended to DestTy.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005046 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5047 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005048
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005049 if (Res2 == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00005050 // Make sure that src sign and dest sign match. For example,
5051 //
5052 // %A = cast short %X to uint
5053 // %B = setgt uint %A, 1330
5054 //
Devang Patel88afd002006-10-19 19:21:36 +00005055 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00005056 //
5057 // %B = setgt short %X, 1330
5058 //
5059 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00005060 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5061 // OR operation is EQ/NE.
5062 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005063 RHSCIOp = Res1;
Devang Patelb42aef42006-10-19 18:54:08 +00005064 else
5065 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005066 } else {
5067 // If the value cannot be represented in the shorter type, we cannot emit
5068 // a simple comparison.
5069 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005070 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005071 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005072 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005073
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005074 // Evaluate the comparison for LT.
5075 Value *Result;
5076 if (DestTy->isSigned()) {
5077 // We're performing a signed comparison.
5078 if (isSignSrc) {
5079 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005080 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005081 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005082 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005083 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005084 } else {
5085 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005086 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005087 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005088 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005089 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005090 }
5091 } else {
5092 // We're performing an unsigned comparison.
5093 if (!isSignSrc) {
5094 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005095 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005096 } else {
5097 // We're performing an unsigned comp with a sign extended value.
5098 // This is true if the input is >= 0. [aka >s -1]
5099 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5100 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5101 NegOne, SCI.getName()), SCI);
5102 }
Reid Spencer279fa252004-11-28 21:31:15 +00005103 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005104
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005105 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005106 if (SCI.getOpcode() == Instruction::SetLT) {
5107 return ReplaceInstUsesWith(SCI, Result);
5108 } else {
5109 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5110 if (Constant *CI = dyn_cast<Constant>(Result))
5111 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5112 else
5113 return BinaryOperator::createNot(Result);
5114 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005115 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005116 } else {
5117 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005118 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005119
Chris Lattner252a8452005-06-16 03:00:08 +00005120 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005121 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5122}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005123
Chris Lattnere8d6c602003-03-10 19:16:08 +00005124Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005125 assert(I.getOperand(1)->getType() == Type::UByteTy);
5126 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005127 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005128
5129 // shl X, 0 == X and shr X, 0 == X
5130 // shl 0, X == 0 and shr 0, X == 0
5131 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005132 Op0 == Constant::getNullValue(Op0->getType()))
5133 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005134
Chris Lattner81a7a232004-10-16 18:11:37 +00005135 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5136 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005137 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005138 else // undef << X -> 0 AND undef >>u X -> 0
5139 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5140 }
5141 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005142 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005143 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5144 else
5145 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5146 }
5147
Chris Lattnerd4dee402006-11-10 23:38:52 +00005148 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5149 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005150 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005151 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005152 return ReplaceInstUsesWith(I, CSI);
5153
Chris Lattner183b3362004-04-09 19:05:30 +00005154 // Try to fold constant and into select arguments.
5155 if (isa<Constant>(Op0))
5156 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005158 return R;
5159
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005160 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005161 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005162 if (MaskedValueIsZero(Op0,
5163 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005164 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005165 }
5166 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005167
Reid Spencere0fc4df2006-10-20 07:07:24 +00005168 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5169 if (CUI->getType()->isUnsigned())
5170 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5171 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005172 return 0;
5173}
5174
Reid Spencere0fc4df2006-10-20 07:07:24 +00005175Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005176 ShiftInst &I) {
5177 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005178 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5179 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005180 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005181
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005182 // See if we can simplify any instructions used by the instruction whose sole
5183 // purpose is to compute bits we don't care about.
5184 uint64_t KnownZero, KnownOne;
5185 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5186 KnownZero, KnownOne))
5187 return &I;
5188
Chris Lattner14553932006-01-06 07:12:35 +00005189 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5190 // of a signed value.
5191 //
5192 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005193 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005194 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005195 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5196 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005197 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005198 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005199 }
Chris Lattner14553932006-01-06 07:12:35 +00005200 }
5201
5202 // ((X*C1) << C2) == (X * (C1 << C2))
5203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5204 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5205 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5206 return BinaryOperator::createMul(BO->getOperand(0),
5207 ConstantExpr::getShl(BOOp, Op1));
5208
5209 // Try to fold constant and into select arguments.
5210 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5211 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5212 return R;
5213 if (isa<PHINode>(Op0))
5214 if (Instruction *NV = FoldOpIntoPhi(I))
5215 return NV;
5216
5217 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005218 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5219 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5220 Value *V1, *V2;
5221 ConstantInt *CC;
5222 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005223 default: break;
5224 case Instruction::Add:
5225 case Instruction::And:
5226 case Instruction::Or:
5227 case Instruction::Xor:
5228 // These operators commute.
5229 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005230 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5231 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005232 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005233 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005234 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005235 Op0BO->getName());
5236 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005237 Instruction *X =
5238 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5239 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005240 InsertNewInstBefore(X, I); // (X + (Y << C))
5241 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005242 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005243 return BinaryOperator::createAnd(X, C2);
5244 }
Chris Lattner14553932006-01-06 07:12:35 +00005245
Chris Lattner797dee72005-09-18 06:30:59 +00005246 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5247 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5248 match(Op0BO->getOperand(1),
5249 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005250 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005251 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005252 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005253 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005254 Op0BO->getName());
5255 InsertNewInstBefore(YS, I); // (Y << C)
5256 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005257 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005258 V1->getName()+".mask");
5259 InsertNewInstBefore(XM, I); // X & (CC << C)
5260
5261 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5262 }
Chris Lattner14553932006-01-06 07:12:35 +00005263
Chris Lattner797dee72005-09-18 06:30:59 +00005264 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005265 case Instruction::Sub:
5266 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005267 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5268 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005269 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005270 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005271 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005272 Op0BO->getName());
5273 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005274 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005275 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005276 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005277 InsertNewInstBefore(X, I); // (X + (Y << C))
5278 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005279 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005280 return BinaryOperator::createAnd(X, C2);
5281 }
Chris Lattner14553932006-01-06 07:12:35 +00005282
Chris Lattner1df0e982006-05-31 21:14:00 +00005283 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005284 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5285 match(Op0BO->getOperand(0),
5286 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005287 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005288 cast<BinaryOperator>(Op0BO->getOperand(0))
5289 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005290 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005291 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005292 Op0BO->getName());
5293 InsertNewInstBefore(YS, I); // (Y << C)
5294 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005295 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005296 V1->getName()+".mask");
5297 InsertNewInstBefore(XM, I); // X & (CC << C)
5298
Chris Lattner1df0e982006-05-31 21:14:00 +00005299 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005300 }
Chris Lattner14553932006-01-06 07:12:35 +00005301
Chris Lattner27cb9db2005-09-18 05:12:10 +00005302 break;
Chris Lattner14553932006-01-06 07:12:35 +00005303 }
5304
5305
5306 // If the operand is an bitwise operator with a constant RHS, and the
5307 // shift is the only use, we can pull it out of the shift.
5308 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5309 bool isValid = true; // Valid only for And, Or, Xor
5310 bool highBitSet = false; // Transform if high bit of constant set?
5311
5312 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005313 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005314 case Instruction::Add:
5315 isValid = isLeftShift;
5316 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005317 case Instruction::Or:
5318 case Instruction::Xor:
5319 highBitSet = false;
5320 break;
5321 case Instruction::And:
5322 highBitSet = true;
5323 break;
Chris Lattner14553932006-01-06 07:12:35 +00005324 }
5325
5326 // If this is a signed shift right, and the high bit is modified
5327 // by the logical operation, do not perform the transformation.
5328 // The highBitSet boolean indicates the value of the high bit of
5329 // the constant which would cause it to be modified for this
5330 // operation.
5331 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005332 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005333 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005334 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5335 }
5336
5337 if (isValid) {
5338 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5339
5340 Instruction *NewShift =
5341 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5342 Op0BO->getName());
5343 Op0BO->setName("");
5344 InsertNewInstBefore(NewShift, I);
5345
5346 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5347 NewRHS);
5348 }
5349 }
5350 }
5351 }
5352
Chris Lattnereb372a02006-01-06 07:52:12 +00005353 // Find out if this is a shift of a shift by a constant.
5354 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005355 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005356 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005357 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5358 // If this is a noop-integer cast of a shift instruction, use the shift.
5359 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005360 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5361 }
5362 }
5363
Reid Spencere0fc4df2006-10-20 07:07:24 +00005364 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005365 // Find the operands and properties of the input shift. Note that the
5366 // signedness of the input shift may differ from the current shift if there
5367 // is a noop cast between the two.
5368 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005369 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5370 ShiftOp->getType()->isSigned() :
5371 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005372 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005373
Reid Spencere0fc4df2006-10-20 07:07:24 +00005374 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005375
Reid Spencere0fc4df2006-10-20 07:07:24 +00005376 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5377 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005378
5379 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5380 if (isLeftShift == isShiftOfLeftShift) {
5381 // Do not fold these shifts if the first one is signed and the second one
5382 // is unsigned and this is a right shift. Further, don't do any folding
5383 // on them.
5384 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5385 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005386
Chris Lattnereb372a02006-01-06 07:52:12 +00005387 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5388 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5389 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005390
Chris Lattnereb372a02006-01-06 07:52:12 +00005391 Value *Op = ShiftOp->getOperand(0);
5392 if (isShiftOfSignedShift != isSignedShift)
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005393 Op = InsertNewInstBefore(new BitCastInst(Op, I.getType(), "tmp"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005394 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005395 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005396 if (I.getType() == ShiftResult->getType())
5397 return ShiftResult;
5398 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005399 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005400 }
5401
5402 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5403 // signed types, we can only support the (A >> c1) << c2 configuration,
5404 // because it can not turn an arbitrary bit of A into a sign bit.
5405 if (isUnsignedShift || isLeftShift) {
5406 // Calculate bitmask for what gets shifted off the edge.
5407 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5408 if (isLeftShift)
5409 C = ConstantExpr::getShl(C, ShiftAmt1C);
5410 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005411 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005412
5413 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005414 if (Op->getType() != C->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00005415 Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005416
5417 Instruction *Mask =
5418 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5419 InsertNewInstBefore(Mask, I);
5420
5421 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005422 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005423 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005424 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005425 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005426 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005427 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5428 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005429 return new ShiftInst(Instruction::LShr, Mask,
5430 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005431 } else {
5432 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005433 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005434 }
5435 } else {
5436 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer13bc5d72006-12-12 09:18:51 +00005437 Op = InsertCastBefore(Instruction::BitCast, Mask,
5438 I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005439 Instruction *Shift =
5440 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005441 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005442 InsertNewInstBefore(Shift, I);
5443
5444 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5445 C = ConstantExpr::getShl(C, Op1);
5446 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5447 InsertNewInstBefore(Mask, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005448 return CastInst::create(Instruction::BitCast, Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005449 }
5450 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005451 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005452 // this case, C1 == C2 and C1 is 8, 16, or 32.
5453 if (ShiftAmt1 == ShiftAmt2) {
5454 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005455 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005456 case 8 : SExtType = Type::SByteTy; break;
5457 case 16: SExtType = Type::ShortTy; break;
5458 case 32: SExtType = Type::IntTy; break;
5459 }
5460
5461 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005462 Instruction *NewTrunc =
5463 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005464 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005465 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005466 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005467 }
Chris Lattner86102b82005-01-01 16:22:27 +00005468 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005469 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005470 return 0;
5471}
5472
Chris Lattner48a44f72002-05-02 17:06:02 +00005473
Chris Lattner8f663e82005-10-29 04:36:15 +00005474/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5475/// expression. If so, decompose it, returning some value X, such that Val is
5476/// X*Scale+Offset.
5477///
5478static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5479 unsigned &Offset) {
5480 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005481 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5482 if (CI->getType()->isUnsigned()) {
5483 Offset = CI->getZExtValue();
5484 Scale = 1;
5485 return ConstantInt::get(Type::UIntTy, 0);
5486 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005487 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5488 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005489 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5490 if (CUI->getType()->isUnsigned()) {
5491 if (I->getOpcode() == Instruction::Shl) {
5492 // This is a value scaled by '1 << the shift amt'.
5493 Scale = 1U << CUI->getZExtValue();
5494 Offset = 0;
5495 return I->getOperand(0);
5496 } else if (I->getOpcode() == Instruction::Mul) {
5497 // This value is scaled by 'CUI'.
5498 Scale = CUI->getZExtValue();
5499 Offset = 0;
5500 return I->getOperand(0);
5501 } else if (I->getOpcode() == Instruction::Add) {
5502 // We have X+C. Check to see if we really have (X*C2)+C1,
5503 // where C1 is divisible by C2.
5504 unsigned SubScale;
5505 Value *SubVal =
5506 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5507 Offset += CUI->getZExtValue();
5508 if (SubScale > 1 && (Offset % SubScale == 0)) {
5509 Scale = SubScale;
5510 return SubVal;
5511 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005512 }
5513 }
5514 }
5515 }
5516 }
5517
5518 // Otherwise, we can't look past this.
5519 Scale = 1;
5520 Offset = 0;
5521 return Val;
5522}
5523
5524
Chris Lattner216be912005-10-24 06:03:58 +00005525/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5526/// try to eliminate the cast by moving the type information into the alloc.
5527Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5528 AllocationInst &AI) {
5529 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005530 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005531
Chris Lattnerac87beb2005-10-24 06:22:12 +00005532 // Remove any uses of AI that are dead.
5533 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5534 std::vector<Instruction*> DeadUsers;
5535 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5536 Instruction *User = cast<Instruction>(*UI++);
5537 if (isInstructionTriviallyDead(User)) {
5538 while (UI != E && *UI == User)
5539 ++UI; // If this instruction uses AI more than once, don't break UI.
5540
5541 // Add operands to the worklist.
5542 AddUsesToWorkList(*User);
5543 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005544 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005545
5546 User->eraseFromParent();
5547 removeFromWorkList(User);
5548 }
5549 }
5550
Chris Lattner216be912005-10-24 06:03:58 +00005551 // Get the type really allocated and the type casted to.
5552 const Type *AllocElTy = AI.getAllocatedType();
5553 const Type *CastElTy = PTy->getElementType();
5554 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005555
Chris Lattner7d190672006-10-01 19:40:58 +00005556 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5557 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005558 if (CastElTyAlign < AllocElTyAlign) return 0;
5559
Chris Lattner46705b22005-10-24 06:35:18 +00005560 // If the allocation has multiple uses, only promote it if we are strictly
5561 // increasing the alignment of the resultant allocation. If we keep it the
5562 // same, we open the door to infinite loops of various kinds.
5563 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5564
Chris Lattner216be912005-10-24 06:03:58 +00005565 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5566 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005567 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005568
Chris Lattner8270c332005-10-29 03:19:53 +00005569 // See if we can satisfy the modulus by pulling a scale out of the array
5570 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005571 unsigned ArraySizeScale, ArrayOffset;
5572 Value *NumElements = // See if the array size is a decomposable linear expr.
5573 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5574
Chris Lattner8270c332005-10-29 03:19:53 +00005575 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5576 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005577 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5578 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005579
Chris Lattner8270c332005-10-29 03:19:53 +00005580 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5581 Value *Amt = 0;
5582 if (Scale == 1) {
5583 Amt = NumElements;
5584 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005585 // If the allocation size is constant, form a constant mul expression
5586 Amt = ConstantInt::get(Type::UIntTy, Scale);
5587 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5588 Amt = ConstantExpr::getMul(
5589 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5590 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005591 else if (Scale != 1) {
5592 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5593 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005594 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005595 }
5596
Chris Lattner8f663e82005-10-29 04:36:15 +00005597 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005598 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005599 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5600 Amt = InsertNewInstBefore(Tmp, AI);
5601 }
5602
Chris Lattner216be912005-10-24 06:03:58 +00005603 std::string Name = AI.getName(); AI.setName("");
5604 AllocationInst *New;
5605 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005606 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005607 else
Nate Begeman848622f2005-11-05 09:21:28 +00005608 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005609 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005610
5611 // If the allocation has multiple uses, insert a cast and change all things
5612 // that used it to use the new cast. This will also hack on CI, but it will
5613 // die soon.
5614 if (!AI.hasOneUse()) {
5615 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005616 // New is the allocation instruction, pointer typed. AI is the original
5617 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5618 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005619 InsertNewInstBefore(NewCast, AI);
5620 AI.replaceAllUsesWith(NewCast);
5621 }
Chris Lattner216be912005-10-24 06:03:58 +00005622 return ReplaceInstUsesWith(CI, New);
5623}
5624
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005625/// CanEvaluateInDifferentType - Return true if we can take the specified value
5626/// and return it without inserting any new casts. This is used by code that
5627/// tries to decide whether promoting or shrinking integer operations to wider
5628/// or smaller types will allow us to eliminate a truncate or extend.
5629static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5630 int &NumCastsRemoved) {
5631 if (isa<Constant>(V)) return true;
5632
5633 Instruction *I = dyn_cast<Instruction>(V);
5634 if (!I || !I->hasOneUse()) return false;
5635
5636 switch (I->getOpcode()) {
5637 case Instruction::And:
5638 case Instruction::Or:
5639 case Instruction::Xor:
5640 // These operators can all arbitrarily be extended or truncated.
5641 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5642 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005643 case Instruction::AShr:
5644 case Instruction::LShr:
5645 case Instruction::Shl:
5646 // If this is just a bitcast changing the sign of the operation, we can
5647 // convert if the operand can be converted.
5648 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5649 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5650 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005651 case Instruction::Trunc:
5652 case Instruction::ZExt:
5653 case Instruction::SExt:
5654 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005655 // If this is a cast from the destination type, we can trivially eliminate
5656 // it, and this will remove a cast overall.
5657 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005658 // If the first operand is itself a cast, and is eliminable, do not count
5659 // this as an eliminable cast. We would prefer to eliminate those two
5660 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005661 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005662 return true;
5663
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005664 ++NumCastsRemoved;
5665 return true;
5666 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005667 break;
5668 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005669 // TODO: Can handle more cases here.
5670 break;
5671 }
5672
5673 return false;
5674}
5675
5676/// EvaluateInDifferentType - Given an expression that
5677/// CanEvaluateInDifferentType returns true for, actually insert the code to
5678/// evaluate the expression.
5679Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5680 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005681 return ConstantExpr::getIntegerCast(C, Ty, C->getType()->isSigned());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005682
5683 // Otherwise, it must be an instruction.
5684 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005685 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005686 switch (I->getOpcode()) {
5687 case Instruction::And:
5688 case Instruction::Or:
5689 case Instruction::Xor: {
5690 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5691 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5692 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5693 LHS, RHS, I->getName());
5694 break;
5695 }
Chris Lattner960acb02006-11-29 07:18:39 +00005696 case Instruction::AShr:
5697 case Instruction::LShr:
5698 case Instruction::Shl: {
5699 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5700 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5701 I->getOperand(1), I->getName());
5702 break;
5703 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005704 case Instruction::Trunc:
5705 case Instruction::ZExt:
5706 case Instruction::SExt:
5707 case Instruction::BitCast:
5708 // If the source type of the cast is the type we're trying for then we can
5709 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005710 if (I->getOperand(0)->getType() == Ty)
5711 return I->getOperand(0);
5712
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005713 // Some other kind of cast, which shouldn't happen, so just ..
5714 // FALL THROUGH
5715 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005716 // TODO: Can handle more cases here.
5717 assert(0 && "Unreachable!");
5718 break;
5719 }
5720
5721 return InsertNewInstBefore(Res, *I);
5722}
5723
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005724/// @brief Implement the transforms common to all CastInst visitors.
5725Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005726 Value *Src = CI.getOperand(0);
5727
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005728 // Casting undef to anything results in undef so might as just replace it and
5729 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005730 if (isa<UndefValue>(Src)) // cast undef -> undef
5731 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5732
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005733 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5734 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005735 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005736 if (Instruction::CastOps opc =
5737 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5738 // The first cast (CSrc) is eliminable so we need to fix up or replace
5739 // the second cast (CI). CSrc will then have a good chance of being dead.
5740 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005741 }
5742 }
Chris Lattner03841652004-05-25 04:29:21 +00005743
Chris Lattnerd0d51602003-06-21 23:12:02 +00005744 // If casting the result of a getelementptr instruction with no offset, turn
5745 // this into a cast of the original pointer!
5746 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005747 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005748 bool AllZeroOperands = true;
5749 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5750 if (!isa<Constant>(GEP->getOperand(i)) ||
5751 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5752 AllZeroOperands = false;
5753 break;
5754 }
5755 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005756 // Changing the cast operand is usually not a good idea but it is safe
5757 // here because the pointer operand is being replaced with another
5758 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005759 CI.setOperand(0, GEP->getOperand(0));
5760 return &CI;
5761 }
5762 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005763
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005764 // If we are casting a malloc or alloca to a pointer to a type of the same
5765 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005766 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005767 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5768 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005769
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005770 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005771 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5772 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5773 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005774
5775 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005776 if (isa<PHINode>(Src))
5777 if (Instruction *NV = FoldOpIntoPhi(CI))
5778 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005779
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005780 return 0;
5781}
5782
5783/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5784/// integers. This function implements the common transforms for all those
5785/// cases.
5786/// @brief Implement the transforms common to CastInst with integer operands
5787Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5788 if (Instruction *Result = commonCastTransforms(CI))
5789 return Result;
5790
5791 Value *Src = CI.getOperand(0);
5792 const Type *SrcTy = Src->getType();
5793 const Type *DestTy = CI.getType();
5794 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5795 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5796
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005797 // See if we can simplify any instructions used by the LHS whose sole
5798 // purpose is to compute bits we don't care about.
5799 uint64_t KnownZero = 0, KnownOne = 0;
5800 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5801 KnownZero, KnownOne))
5802 return &CI;
5803
5804 // If the source isn't an instruction or has more than one use then we
5805 // can't do anything more.
5806 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5807 return 0;
5808
5809 // Attempt to propagate the cast into the instruction.
5810 Instruction *SrcI = cast<Instruction>(Src);
5811 int NumCastsRemoved = 0;
5812 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5813 // If this cast is a truncate, evaluting in a different type always
5814 // eliminates the cast, so it is always a win. If this is a noop-cast
5815 // this just removes a noop cast which isn't pointful, but simplifies
5816 // the code. If this is a zero-extension, we need to do an AND to
5817 // maintain the clear top-part of the computation, so we require that
5818 // the input have eliminated at least one cast. If this is a sign
5819 // extension, we insert two new casts (to do the extension) so we
5820 // require that two casts have been eliminated.
5821 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5822 if (!DoXForm) {
5823 switch (CI.getOpcode()) {
5824 case Instruction::Trunc:
5825 DoXForm = true;
5826 break;
5827 case Instruction::ZExt:
5828 DoXForm = NumCastsRemoved >= 1;
5829 break;
5830 case Instruction::SExt:
5831 DoXForm = NumCastsRemoved >= 2;
5832 break;
5833 case Instruction::BitCast:
5834 DoXForm = false;
5835 break;
5836 default:
5837 // All the others use floating point so we shouldn't actually
5838 // get here because of the check above.
5839 assert(!"Unknown cast type .. unreachable");
5840 break;
5841 }
5842 }
5843
5844 if (DoXForm) {
5845 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5846 assert(Res->getType() == DestTy);
5847 switch (CI.getOpcode()) {
5848 default: assert(0 && "Unknown cast type!");
5849 case Instruction::Trunc:
5850 case Instruction::BitCast:
5851 // Just replace this cast with the result.
5852 return ReplaceInstUsesWith(CI, Res);
5853 case Instruction::ZExt: {
5854 // We need to emit an AND to clear the high bits.
5855 assert(SrcBitSize < DestBitSize && "Not a zext?");
5856 Constant *C =
5857 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5858 if (DestBitSize < 64)
5859 C = ConstantExpr::getTrunc(C, DestTy);
5860 else {
5861 assert(DestBitSize == 64);
5862 C = ConstantExpr::getBitCast(C, DestTy);
5863 }
5864 return BinaryOperator::createAnd(Res, C);
5865 }
5866 case Instruction::SExt:
5867 // We need to emit a cast to truncate, then a cast to sext.
5868 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00005869 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
5870 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005871 }
5872 }
5873 }
5874
5875 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5876 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5877
5878 switch (SrcI->getOpcode()) {
5879 case Instruction::Add:
5880 case Instruction::Mul:
5881 case Instruction::And:
5882 case Instruction::Or:
5883 case Instruction::Xor:
5884 // If we are discarding information, or just changing the sign,
5885 // rewrite.
5886 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5887 // Don't insert two casts if they cannot be eliminated. We allow
5888 // two casts to be inserted if the sizes are the same. This could
5889 // only be converting signedness, which is a noop.
5890 if (DestBitSize == SrcBitSize ||
5891 !ValueRequiresCast(Op1, DestTy,TD) ||
5892 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005893 unsigned Op0BitSize = Op0->getType()->getPrimitiveSizeInBits();
5894 Instruction::CastOps opcode =
5895 (Op0BitSize > DestBitSize ? Instruction::Trunc :
5896 (Op0BitSize == DestBitSize ? Instruction::BitCast :
5897 Op0->getType()->isSigned() ? Instruction::SExt :Instruction::ZExt));
5898 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
5899 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
5900 return BinaryOperator::create(
5901 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005902 }
5903 }
5904
5905 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5906 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5907 SrcI->getOpcode() == Instruction::Xor &&
5908 Op1 == ConstantBool::getTrue() &&
5909 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005910 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005911 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5912 }
5913 break;
5914 case Instruction::SDiv:
5915 case Instruction::UDiv:
5916 case Instruction::SRem:
5917 case Instruction::URem:
5918 // If we are just changing the sign, rewrite.
5919 if (DestBitSize == SrcBitSize) {
5920 // Don't insert two casts if they cannot be eliminated. We allow
5921 // two casts to be inserted if the sizes are the same. This could
5922 // only be converting signedness, which is a noop.
5923 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5924 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005925 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
5926 Op0, DestTy, SrcI);
5927 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
5928 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005929 return BinaryOperator::create(
5930 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5931 }
5932 }
5933 break;
5934
5935 case Instruction::Shl:
5936 // Allow changing the sign of the source operand. Do not allow
5937 // changing the size of the shift, UNLESS the shift amount is a
5938 // constant. We must not change variable sized shifts to a smaller
5939 // size, because it is undefined to shift more bits out than exist
5940 // in the value.
5941 if (DestBitSize == SrcBitSize ||
5942 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005943 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
5944 Instruction::BitCast : Instruction::Trunc);
5945 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005946 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5947 }
5948 break;
5949 case Instruction::AShr:
5950 // If this is a signed shr, and if all bits shifted in are about to be
5951 // truncated off, turn it into an unsigned shr to allow greater
5952 // simplifications.
5953 if (DestBitSize < SrcBitSize &&
5954 isa<ConstantInt>(Op1)) {
5955 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5956 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5957 // Insert the new logical shift right.
5958 return new ShiftInst(Instruction::LShr, Op0, Op1);
5959 }
5960 }
5961 break;
5962
5963 case Instruction::SetEQ:
5964 case Instruction::SetNE:
5965 // If we are just checking for a seteq of a single bit and casting it
5966 // to an integer. If so, shift the bit to the appropriate place then
5967 // cast to integer to avoid the comparison.
5968 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5969 uint64_t Op1CV = Op1C->getZExtValue();
5970 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5971 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5972 // cast (X == 1) to int --> X iff X has only the low bit set.
5973 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5974 // cast (X != 0) to int --> X iff X has only the low bit set.
5975 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5976 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5977 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5978 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5979 // If Op1C some other power of two, convert:
5980 uint64_t KnownZero, KnownOne;
5981 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5982 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5983
5984 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5985 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5986 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5987 // (X&4) == 2 --> false
5988 // (X&4) != 2 --> true
5989 Constant *Res = ConstantBool::get(isSetNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005990 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005991 return ReplaceInstUsesWith(CI, Res);
5992 }
5993
5994 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5995 Value *In = Op0;
5996 if (ShiftAmt) {
5997 // Perform a logical shr by shiftamt.
5998 // Insert the shift to put the result in the low bit.
5999 In = InsertNewInstBefore(
6000 new ShiftInst(Instruction::LShr, In,
6001 ConstantInt::get(Type::UByteTy, ShiftAmt),
6002 In->getName()+".lobit"), CI);
6003 }
6004
6005 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
6006 Constant *One = ConstantInt::get(In->getType(), 1);
6007 In = BinaryOperator::createXor(In, One, "tmp");
6008 InsertNewInstBefore(cast<Instruction>(In), CI);
6009 }
6010
6011 if (CI.getType() == In->getType())
6012 return ReplaceInstUsesWith(CI, In);
6013 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006014 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006015 }
6016 }
6017 }
6018 break;
6019 }
6020 return 0;
6021}
6022
6023Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006024 if (Instruction *Result = commonIntCastTransforms(CI))
6025 return Result;
6026
6027 Value *Src = CI.getOperand(0);
6028 const Type *Ty = CI.getType();
6029 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6030
6031 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6032 switch (SrcI->getOpcode()) {
6033 default: break;
6034 case Instruction::LShr:
6035 // We can shrink lshr to something smaller if we know the bits shifted in
6036 // are already zeros.
6037 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6038 unsigned ShAmt = ShAmtV->getZExtValue();
6039
6040 // Get a mask for the bits shifting in.
6041 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006042 Value* SrcIOp0 = SrcI->getOperand(0);
6043 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006044 if (ShAmt >= DestBitWidth) // All zeros.
6045 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6046
6047 // Okay, we can shrink this. Truncate the input, then return a new
6048 // shift.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006049 Instruction::CastOps opcode =
6050 (SrcIOp0->getType()->getPrimitiveSizeInBits() ==
6051 Ty->getPrimitiveSizeInBits() ? Instruction::BitCast :
6052 Instruction::Trunc);
6053 Value *V = InsertCastBefore(opcode, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006054 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6055 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006056 } else { // This is a variable shr.
6057
6058 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6059 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6060 // loop-invariant and CSE'd.
6061 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6062 Value *One = ConstantInt::get(SrcI->getType(), 1);
6063
6064 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6065 SrcI->getOperand(1),
6066 "tmp"), CI);
6067 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6068 SrcI->getOperand(0),
6069 "tmp"), CI);
6070 Value *Zero = Constant::getNullValue(V->getType());
6071 return BinaryOperator::createSetNE(V, Zero);
6072 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006073 }
6074 break;
6075 }
6076 }
6077
6078 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006079}
6080
6081Instruction *InstCombiner::visitZExt(CastInst &CI) {
6082 // If one of the common conversion will work ..
6083 if (Instruction *Result = commonIntCastTransforms(CI))
6084 return Result;
6085
6086 Value *Src = CI.getOperand(0);
6087
6088 // If this is a cast of a cast
6089 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006090 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6091 // types and if the sizes are just right we can convert this into a logical
6092 // 'and' which will be much cheaper than the pair of casts.
6093 if (isa<TruncInst>(CSrc)) {
6094 // Get the sizes of the types involved
6095 Value *A = CSrc->getOperand(0);
6096 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6097 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6098 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6099 // If we're actually extending zero bits and the trunc is a no-op
6100 if (MidSize < DstSize && SrcSize == DstSize) {
6101 // Replace both of the casts with an And of the type mask.
6102 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6103 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6104 Instruction *And =
6105 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6106 // Unfortunately, if the type changed, we need to cast it back.
6107 if (And->getType() != CI.getType()) {
6108 And->setName(CSrc->getName()+".mask");
6109 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006110 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006111 }
6112 return And;
6113 }
6114 }
6115 }
6116
6117 return 0;
6118}
6119
6120Instruction *InstCombiner::visitSExt(CastInst &CI) {
6121 return commonIntCastTransforms(CI);
6122}
6123
6124Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6125 return commonCastTransforms(CI);
6126}
6127
6128Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6129 return commonCastTransforms(CI);
6130}
6131
6132Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006133 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006134}
6135
6136Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006137 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006138}
6139
6140Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6141 return commonCastTransforms(CI);
6142}
6143
6144Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6145 return commonCastTransforms(CI);
6146}
6147
6148Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006149 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006150}
6151
6152Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6153 return commonCastTransforms(CI);
6154}
6155
6156Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6157
6158 // If the operands are integer typed then apply the integer transforms,
6159 // otherwise just apply the common ones.
6160 Value *Src = CI.getOperand(0);
6161 const Type *SrcTy = Src->getType();
6162 const Type *DestTy = CI.getType();
6163
6164 if (SrcTy->isInteger() && DestTy->isInteger()) {
6165 if (Instruction *Result = commonIntCastTransforms(CI))
6166 return Result;
6167 } else {
6168 if (Instruction *Result = commonCastTransforms(CI))
6169 return Result;
6170 }
6171
6172
6173 // Get rid of casts from one type to the same type. These are useless and can
6174 // be replaced by the operand.
6175 if (DestTy == Src->getType())
6176 return ReplaceInstUsesWith(CI, Src);
6177
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006178 // If the source and destination are pointers, and this cast is equivalent to
6179 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6180 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006181 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6182 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6183 const Type *DstElTy = DstPTy->getElementType();
6184 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006185
6186 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6187 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006188 while (SrcElTy != DstElTy &&
6189 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6190 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6191 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006192 ++NumZeros;
6193 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006194
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006195 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006196 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006197 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6198 return new GetElementPtrInst(Src, Idxs);
6199 }
6200 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006201 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006202
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006203 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6204 if (SVI->hasOneUse()) {
6205 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6206 // a bitconvert to a vector with the same # elts.
6207 if (isa<PackedType>(DestTy) &&
6208 cast<PackedType>(DestTy)->getNumElements() ==
6209 SVI->getType()->getNumElements()) {
6210 CastInst *Tmp;
6211 // If either of the operands is a cast from CI.getType(), then
6212 // evaluating the shuffle in the casted destination's type will allow
6213 // us to eliminate at least one cast.
6214 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6215 Tmp->getOperand(0)->getType() == DestTy) ||
6216 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6217 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006218 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6219 SVI->getOperand(0), DestTy, &CI);
6220 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6221 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006222 // Return a new shuffle vector. Use the same element ID's, as we
6223 // know the vector types match #elts.
6224 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006225 }
6226 }
6227 }
6228 }
Chris Lattner260ab202002-04-18 17:39:14 +00006229 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006230}
6231
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006232/// GetSelectFoldableOperands - We want to turn code that looks like this:
6233/// %C = or %A, %B
6234/// %D = select %cond, %C, %A
6235/// into:
6236/// %C = select %cond, %B, 0
6237/// %D = or %A, %C
6238///
6239/// Assuming that the specified instruction is an operand to the select, return
6240/// a bitmask indicating which operands of this instruction are foldable if they
6241/// equal the other incoming value of the select.
6242///
6243static unsigned GetSelectFoldableOperands(Instruction *I) {
6244 switch (I->getOpcode()) {
6245 case Instruction::Add:
6246 case Instruction::Mul:
6247 case Instruction::And:
6248 case Instruction::Or:
6249 case Instruction::Xor:
6250 return 3; // Can fold through either operand.
6251 case Instruction::Sub: // Can only fold on the amount subtracted.
6252 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006253 case Instruction::LShr:
6254 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006255 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006256 default:
6257 return 0; // Cannot fold
6258 }
6259}
6260
6261/// GetSelectFoldableConstant - For the same transformation as the previous
6262/// function, return the identity constant that goes into the select.
6263static Constant *GetSelectFoldableConstant(Instruction *I) {
6264 switch (I->getOpcode()) {
6265 default: assert(0 && "This cannot happen!"); abort();
6266 case Instruction::Add:
6267 case Instruction::Sub:
6268 case Instruction::Or:
6269 case Instruction::Xor:
6270 return Constant::getNullValue(I->getType());
6271 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006272 case Instruction::LShr:
6273 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006274 return Constant::getNullValue(Type::UByteTy);
6275 case Instruction::And:
6276 return ConstantInt::getAllOnesValue(I->getType());
6277 case Instruction::Mul:
6278 return ConstantInt::get(I->getType(), 1);
6279 }
6280}
6281
Chris Lattner411336f2005-01-19 21:50:18 +00006282/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6283/// have the same opcode and only one use each. Try to simplify this.
6284Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6285 Instruction *FI) {
6286 if (TI->getNumOperands() == 1) {
6287 // If this is a non-volatile load or a cast from the same type,
6288 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006289 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006290 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6291 return 0;
6292 } else {
6293 return 0; // unknown unary op.
6294 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006295
Chris Lattner411336f2005-01-19 21:50:18 +00006296 // Fold this by inserting a select from the input values.
6297 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6298 FI->getOperand(0), SI.getName()+".v");
6299 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006300 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6301 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006302 }
6303
6304 // Only handle binary operators here.
6305 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6306 return 0;
6307
6308 // Figure out if the operations have any operands in common.
6309 Value *MatchOp, *OtherOpT, *OtherOpF;
6310 bool MatchIsOpZero;
6311 if (TI->getOperand(0) == FI->getOperand(0)) {
6312 MatchOp = TI->getOperand(0);
6313 OtherOpT = TI->getOperand(1);
6314 OtherOpF = FI->getOperand(1);
6315 MatchIsOpZero = true;
6316 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6317 MatchOp = TI->getOperand(1);
6318 OtherOpT = TI->getOperand(0);
6319 OtherOpF = FI->getOperand(0);
6320 MatchIsOpZero = false;
6321 } else if (!TI->isCommutative()) {
6322 return 0;
6323 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6324 MatchOp = TI->getOperand(0);
6325 OtherOpT = TI->getOperand(1);
6326 OtherOpF = FI->getOperand(0);
6327 MatchIsOpZero = true;
6328 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6329 MatchOp = TI->getOperand(1);
6330 OtherOpT = TI->getOperand(0);
6331 OtherOpF = FI->getOperand(1);
6332 MatchIsOpZero = true;
6333 } else {
6334 return 0;
6335 }
6336
6337 // If we reach here, they do have operations in common.
6338 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6339 OtherOpF, SI.getName()+".v");
6340 InsertNewInstBefore(NewSI, SI);
6341
6342 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6343 if (MatchIsOpZero)
6344 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6345 else
6346 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6347 } else {
6348 if (MatchIsOpZero)
6349 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6350 else
6351 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6352 }
6353}
6354
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006355Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006356 Value *CondVal = SI.getCondition();
6357 Value *TrueVal = SI.getTrueValue();
6358 Value *FalseVal = SI.getFalseValue();
6359
6360 // select true, X, Y -> X
6361 // select false, X, Y -> Y
6362 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006363 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006364
6365 // select C, X, X -> X
6366 if (TrueVal == FalseVal)
6367 return ReplaceInstUsesWith(SI, TrueVal);
6368
Chris Lattner81a7a232004-10-16 18:11:37 +00006369 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6370 return ReplaceInstUsesWith(SI, FalseVal);
6371 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6372 return ReplaceInstUsesWith(SI, TrueVal);
6373 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6374 if (isa<Constant>(TrueVal))
6375 return ReplaceInstUsesWith(SI, TrueVal);
6376 else
6377 return ReplaceInstUsesWith(SI, FalseVal);
6378 }
6379
Chris Lattner1c631e82004-04-08 04:43:23 +00006380 if (SI.getType() == Type::BoolTy)
6381 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006382 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006383 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006384 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006385 } else {
6386 // Change: A = select B, false, C --> A = and !B, C
6387 Value *NotCond =
6388 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6389 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006390 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006391 }
6392 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006393 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006394 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006395 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006396 } else {
6397 // Change: A = select B, C, true --> A = or !B, C
6398 Value *NotCond =
6399 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6400 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006401 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006402 }
6403 }
6404
Chris Lattner183b3362004-04-09 19:05:30 +00006405 // Selecting between two integer constants?
6406 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6407 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6408 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006409 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006410 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006411 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006412 // select C, 0, 1 -> cast !C to int
6413 Value *NotCond =
6414 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006415 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006417 }
Chris Lattner35167c32004-06-09 07:59:58 +00006418
Chris Lattner380c7e92006-09-20 04:44:59 +00006419 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6420
6421 // (x <s 0) ? -1 : 0 -> sra x, 31
6422 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6423 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6424 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6425 bool CanXForm = false;
6426 if (CmpCst->getType()->isSigned())
6427 CanXForm = CmpCst->isNullValue() &&
6428 IC->getOpcode() == Instruction::SetLT;
6429 else {
6430 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006431 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006432 IC->getOpcode() == Instruction::SetGT;
6433 }
6434
6435 if (CanXForm) {
6436 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006437 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006438 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006439 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006440 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006441 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006442 ShAmt, "ones");
6443 InsertNewInstBefore(SRA, SI);
6444
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006445 // Finally, convert to the type of the select RHS. We figure out
6446 // if this requires a SExt, Trunc or BitCast based on the sizes.
6447 Instruction::CastOps opc = Instruction::BitCast;
6448 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6449 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6450 if (SRASize < SISize)
6451 opc = Instruction::SExt;
6452 else if (SRASize > SISize)
6453 opc = Instruction::Trunc;
6454 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006455 }
6456 }
6457
6458
6459 // If one of the constants is zero (we know they can't both be) and we
6460 // have a setcc instruction with zero, and we have an 'and' with the
6461 // non-constant value, eliminate this whole mess. This corresponds to
6462 // cases like this: ((X & 27) ? 27 : 0)
6463 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006464 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006465 cast<Constant>(IC->getOperand(1))->isNullValue())
6466 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6467 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006468 isa<ConstantInt>(ICA->getOperand(1)) &&
6469 (ICA->getOperand(1) == TrueValC ||
6470 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006471 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6472 // Okay, now we know that everything is set up, we just don't
6473 // know whether we have a setne or seteq and whether the true or
6474 // false val is the zero.
6475 bool ShouldNotVal = !TrueValC->isNullValue();
6476 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6477 Value *V = ICA;
6478 if (ShouldNotVal)
6479 V = InsertNewInstBefore(BinaryOperator::create(
6480 Instruction::Xor, V, ICA->getOperand(1)), SI);
6481 return ReplaceInstUsesWith(SI, V);
6482 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006483 }
Chris Lattner533bc492004-03-30 19:37:13 +00006484 }
Chris Lattner623fba12004-04-10 22:21:27 +00006485
6486 // See if we are selecting two values based on a comparison of the two values.
6487 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6488 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6489 // Transform (X == Y) ? X : Y -> Y
6490 if (SCI->getOpcode() == Instruction::SetEQ)
6491 return ReplaceInstUsesWith(SI, FalseVal);
6492 // Transform (X != Y) ? X : Y -> X
6493 if (SCI->getOpcode() == Instruction::SetNE)
6494 return ReplaceInstUsesWith(SI, TrueVal);
6495 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6496
6497 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6498 // Transform (X == Y) ? Y : X -> X
6499 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006500 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006501 // Transform (X != Y) ? Y : X -> Y
6502 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006503 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006504 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6505 }
6506 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006507
Chris Lattnera04c9042005-01-13 22:52:24 +00006508 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6509 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6510 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006511 Instruction *AddOp = 0, *SubOp = 0;
6512
Chris Lattner411336f2005-01-19 21:50:18 +00006513 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6514 if (TI->getOpcode() == FI->getOpcode())
6515 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6516 return IV;
6517
6518 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6519 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006520 if (TI->getOpcode() == Instruction::Sub &&
6521 FI->getOpcode() == Instruction::Add) {
6522 AddOp = FI; SubOp = TI;
6523 } else if (FI->getOpcode() == Instruction::Sub &&
6524 TI->getOpcode() == Instruction::Add) {
6525 AddOp = TI; SubOp = FI;
6526 }
6527
6528 if (AddOp) {
6529 Value *OtherAddOp = 0;
6530 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6531 OtherAddOp = AddOp->getOperand(1);
6532 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6533 OtherAddOp = AddOp->getOperand(0);
6534 }
6535
6536 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006537 // So at this point we know we have (Y -> OtherAddOp):
6538 // select C, (add X, Y), (sub X, Z)
6539 Value *NegVal; // Compute -Z
6540 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6541 NegVal = ConstantExpr::getNeg(C);
6542 } else {
6543 NegVal = InsertNewInstBefore(
6544 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006545 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006546
6547 Value *NewTrueOp = OtherAddOp;
6548 Value *NewFalseOp = NegVal;
6549 if (AddOp != TI)
6550 std::swap(NewTrueOp, NewFalseOp);
6551 Instruction *NewSel =
6552 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6553
6554 NewSel = InsertNewInstBefore(NewSel, SI);
6555 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006556 }
6557 }
6558 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006559
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006560 // See if we can fold the select into one of our operands.
6561 if (SI.getType()->isInteger()) {
6562 // See the comment above GetSelectFoldableOperands for a description of the
6563 // transformation we are doing here.
6564 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6565 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6566 !isa<Constant>(FalseVal))
6567 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6568 unsigned OpToFold = 0;
6569 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6570 OpToFold = 1;
6571 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6572 OpToFold = 2;
6573 }
6574
6575 if (OpToFold) {
6576 Constant *C = GetSelectFoldableConstant(TVI);
6577 std::string Name = TVI->getName(); TVI->setName("");
6578 Instruction *NewSel =
6579 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6580 Name);
6581 InsertNewInstBefore(NewSel, SI);
6582 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6583 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6584 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6585 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6586 else {
6587 assert(0 && "Unknown instruction!!");
6588 }
6589 }
6590 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006591
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006592 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6593 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6594 !isa<Constant>(TrueVal))
6595 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6596 unsigned OpToFold = 0;
6597 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6598 OpToFold = 1;
6599 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6600 OpToFold = 2;
6601 }
6602
6603 if (OpToFold) {
6604 Constant *C = GetSelectFoldableConstant(FVI);
6605 std::string Name = FVI->getName(); FVI->setName("");
6606 Instruction *NewSel =
6607 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6608 Name);
6609 InsertNewInstBefore(NewSel, SI);
6610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6611 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6612 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6613 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6614 else {
6615 assert(0 && "Unknown instruction!!");
6616 }
6617 }
6618 }
6619 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006620
6621 if (BinaryOperator::isNot(CondVal)) {
6622 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6623 SI.setOperand(1, FalseVal);
6624 SI.setOperand(2, TrueVal);
6625 return &SI;
6626 }
6627
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006628 return 0;
6629}
6630
Chris Lattner82f2ef22006-03-06 20:18:44 +00006631/// GetKnownAlignment - If the specified pointer has an alignment that we can
6632/// determine, return it, otherwise return 0.
6633static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6634 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6635 unsigned Align = GV->getAlignment();
6636 if (Align == 0 && TD)
6637 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6638 return Align;
6639 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6640 unsigned Align = AI->getAlignment();
6641 if (Align == 0 && TD) {
6642 if (isa<AllocaInst>(AI))
6643 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6644 else if (isa<MallocInst>(AI)) {
6645 // Malloc returns maximally aligned memory.
6646 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6647 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6648 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6649 }
6650 }
6651 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006652 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006653 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006654 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006655 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006656 if (isa<PointerType>(CI->getOperand(0)->getType()))
6657 return GetKnownAlignment(CI->getOperand(0), TD);
6658 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006659 } else if (isa<GetElementPtrInst>(V) ||
6660 (isa<ConstantExpr>(V) &&
6661 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6662 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006663 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6664 if (BaseAlignment == 0) return 0;
6665
6666 // If all indexes are zero, it is just the alignment of the base pointer.
6667 bool AllZeroOperands = true;
6668 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6669 if (!isa<Constant>(GEPI->getOperand(i)) ||
6670 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6671 AllZeroOperands = false;
6672 break;
6673 }
6674 if (AllZeroOperands)
6675 return BaseAlignment;
6676
6677 // Otherwise, if the base alignment is >= the alignment we expect for the
6678 // base pointer type, then we know that the resultant pointer is aligned at
6679 // least as much as its type requires.
6680 if (!TD) return 0;
6681
6682 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6683 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006684 <= BaseAlignment) {
6685 const Type *GEPTy = GEPI->getType();
6686 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6687 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006688 return 0;
6689 }
6690 return 0;
6691}
6692
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006693
Chris Lattnerc66b2232006-01-13 20:11:04 +00006694/// visitCallInst - CallInst simplification. This mostly only handles folding
6695/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6696/// the heavy lifting.
6697///
Chris Lattner970c33a2003-06-19 17:00:31 +00006698Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6700 if (!II) return visitCallSite(&CI);
6701
Chris Lattner51ea1272004-02-28 05:22:00 +00006702 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6703 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006704 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006705 bool Changed = false;
6706
6707 // memmove/cpy/set of zero bytes is a noop.
6708 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6709 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6710
Chris Lattner00648e12004-10-12 04:52:52 +00006711 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006712 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006713 // Replace the instruction with just byte operations. We would
6714 // transform other cases to loads/stores, but we don't know if
6715 // alignment is sufficient.
6716 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006717 }
6718
Chris Lattner00648e12004-10-12 04:52:52 +00006719 // If we have a memmove and the source operation is a constant global,
6720 // then the source and dest pointers can't alias, so we can change this
6721 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006722 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006723 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6724 if (GVSrc->isConstant()) {
6725 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006726 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006727 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006728 Type::UIntTy)
6729 Name = "llvm.memcpy.i32";
6730 else
6731 Name = "llvm.memcpy.i64";
6732 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006733 CI.getCalledFunction()->getFunctionType());
6734 CI.setOperand(0, MemCpy);
6735 Changed = true;
6736 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006737 }
Chris Lattner00648e12004-10-12 04:52:52 +00006738
Chris Lattner82f2ef22006-03-06 20:18:44 +00006739 // If we can determine a pointer alignment that is bigger than currently
6740 // set, update the alignment.
6741 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6742 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6743 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6744 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006745 if (MI->getAlignment()->getZExtValue() < Align) {
6746 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006747 Changed = true;
6748 }
6749 } else if (isa<MemSetInst>(MI)) {
6750 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006751 if (MI->getAlignment()->getZExtValue() < Alignment) {
6752 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006753 Changed = true;
6754 }
6755 }
6756
Chris Lattnerc66b2232006-01-13 20:11:04 +00006757 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006758 } else {
6759 switch (II->getIntrinsicID()) {
6760 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006761 case Intrinsic::ppc_altivec_lvx:
6762 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006763 case Intrinsic::x86_sse_loadu_ps:
6764 case Intrinsic::x86_sse2_loadu_pd:
6765 case Intrinsic::x86_sse2_loadu_dq:
6766 // Turn PPC lvx -> load if the pointer is known aligned.
6767 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006768 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006769 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006770 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006771 return new LoadInst(Ptr);
6772 }
6773 break;
6774 case Intrinsic::ppc_altivec_stvx:
6775 case Intrinsic::ppc_altivec_stvxl:
6776 // Turn stvx -> store if the pointer is known aligned.
6777 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006778 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006779 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6780 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006781 return new StoreInst(II->getOperand(1), Ptr);
6782 }
6783 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006784 case Intrinsic::x86_sse_storeu_ps:
6785 case Intrinsic::x86_sse2_storeu_pd:
6786 case Intrinsic::x86_sse2_storeu_dq:
6787 case Intrinsic::x86_sse2_storel_dq:
6788 // Turn X86 storeu -> store if the pointer is known aligned.
6789 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6790 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006791 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6792 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00006793 return new StoreInst(II->getOperand(2), Ptr);
6794 }
6795 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006796
6797 case Intrinsic::x86_sse_cvttss2si: {
6798 // These intrinsics only demands the 0th element of its input vector. If
6799 // we can simplify the input based on that, do so now.
6800 uint64_t UndefElts;
6801 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6802 UndefElts)) {
6803 II->setOperand(1, V);
6804 return II;
6805 }
6806 break;
6807 }
6808
Chris Lattnere79d2492006-04-06 19:19:17 +00006809 case Intrinsic::ppc_altivec_vperm:
6810 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6811 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6812 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6813
6814 // Check that all of the elements are integer constants or undefs.
6815 bool AllEltsOk = true;
6816 for (unsigned i = 0; i != 16; ++i) {
6817 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6818 !isa<UndefValue>(Mask->getOperand(i))) {
6819 AllEltsOk = false;
6820 break;
6821 }
6822 }
6823
6824 if (AllEltsOk) {
6825 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006826 Value *Op0 = InsertCastBefore(Instruction::BitCast,
6827 II->getOperand(1), Mask->getType(), CI);
6828 Value *Op1 = InsertCastBefore(Instruction::BitCast,
6829 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00006830 Value *Result = UndefValue::get(Op0->getType());
6831
6832 // Only extract each element once.
6833 Value *ExtractedElts[32];
6834 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6835
6836 for (unsigned i = 0; i != 16; ++i) {
6837 if (isa<UndefValue>(Mask->getOperand(i)))
6838 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006839 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006840 Idx &= 31; // Match the hardware behavior.
6841
6842 if (ExtractedElts[Idx] == 0) {
6843 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006844 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006845 InsertNewInstBefore(Elt, CI);
6846 ExtractedElts[Idx] = Elt;
6847 }
6848
6849 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006850 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006851 InsertNewInstBefore(cast<Instruction>(Result), CI);
6852 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006853 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00006854 }
6855 }
6856 break;
6857
Chris Lattner503221f2006-01-13 21:28:09 +00006858 case Intrinsic::stackrestore: {
6859 // If the save is right next to the restore, remove the restore. This can
6860 // happen when variable allocas are DCE'd.
6861 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6862 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6863 BasicBlock::iterator BI = SS;
6864 if (&*++BI == II)
6865 return EraseInstFromFunction(CI);
6866 }
6867 }
6868
6869 // If the stack restore is in a return/unwind block and if there are no
6870 // allocas or calls between the restore and the return, nuke the restore.
6871 TerminatorInst *TI = II->getParent()->getTerminator();
6872 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6873 BasicBlock::iterator BI = II;
6874 bool CannotRemove = false;
6875 for (++BI; &*BI != TI; ++BI) {
6876 if (isa<AllocaInst>(BI) ||
6877 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6878 CannotRemove = true;
6879 break;
6880 }
6881 }
6882 if (!CannotRemove)
6883 return EraseInstFromFunction(CI);
6884 }
6885 break;
6886 }
6887 }
Chris Lattner00648e12004-10-12 04:52:52 +00006888 }
6889
Chris Lattnerc66b2232006-01-13 20:11:04 +00006890 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006891}
6892
6893// InvokeInst simplification
6894//
6895Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006896 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006897}
6898
Chris Lattneraec3d942003-10-07 22:32:43 +00006899// visitCallSite - Improvements for call and invoke instructions.
6900//
6901Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006902 bool Changed = false;
6903
6904 // If the callee is a constexpr cast of a function, attempt to move the cast
6905 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006906 if (transformConstExprCastCall(CS)) return 0;
6907
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006908 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006909
Chris Lattner61d9d812005-05-13 07:09:09 +00006910 if (Function *CalleeF = dyn_cast<Function>(Callee))
6911 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6912 Instruction *OldCall = CS.getInstruction();
6913 // If the call and callee calling conventions don't match, this call must
6914 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006915 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006916 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6917 if (!OldCall->use_empty())
6918 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6919 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6920 return EraseInstFromFunction(*OldCall);
6921 return 0;
6922 }
6923
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006924 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6925 // This instruction is not reachable, just remove it. We insert a store to
6926 // undef so that we know that this code is not reachable, despite the fact
6927 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006928 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006929 UndefValue::get(PointerType::get(Type::BoolTy)),
6930 CS.getInstruction());
6931
6932 if (!CS.getInstruction()->use_empty())
6933 CS.getInstruction()->
6934 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6935
6936 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6937 // Don't break the CFG, insert a dummy cond branch.
6938 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006939 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006940 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006941 return EraseInstFromFunction(*CS.getInstruction());
6942 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006943
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006944 const PointerType *PTy = cast<PointerType>(Callee->getType());
6945 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6946 if (FTy->isVarArg()) {
6947 // See if we can optimize any arguments passed through the varargs area of
6948 // the call.
6949 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6950 E = CS.arg_end(); I != E; ++I)
6951 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6952 // If this cast does not effect the value passed through the varargs
6953 // area, we can eliminate the use of the cast.
6954 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006955 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006956 *I = Op;
6957 Changed = true;
6958 }
6959 }
6960 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006961
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006962 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006963}
6964
Chris Lattner970c33a2003-06-19 17:00:31 +00006965// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6966// attempt to move the cast to the arguments of the call/invoke.
6967//
6968bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6969 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6970 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006971 if (CE->getOpcode() != Instruction::BitCast ||
6972 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006973 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006974 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006975 Instruction *Caller = CS.getInstruction();
6976
6977 // Okay, this is a cast from a function to a different type. Unless doing so
6978 // would cause a type conversion of one of our arguments, change this call to
6979 // be a direct call with arguments casted to the appropriate types.
6980 //
6981 const FunctionType *FT = Callee->getFunctionType();
6982 const Type *OldRetTy = Caller->getType();
6983
Chris Lattner1f7942f2004-01-14 06:06:08 +00006984 // Check to see if we are changing the return type...
6985 if (OldRetTy != FT->getReturnType()) {
6986 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006987 !Caller->use_empty() &&
6988 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00006989 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006990 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6991 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00006992 return false; // Cannot transform this return value...
6993
6994 // If the callsite is an invoke instruction, and the return value is used by
6995 // a PHI node in a successor, we cannot change the return type of the call
6996 // because there is no place to put the cast instruction (without breaking
6997 // the critical edge). Bail out in this case.
6998 if (!Caller->use_empty())
6999 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7000 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7001 UI != E; ++UI)
7002 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7003 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007004 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007005 return false;
7006 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007007
7008 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7009 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007010
Chris Lattner970c33a2003-06-19 17:00:31 +00007011 CallSite::arg_iterator AI = CS.arg_begin();
7012 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7013 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007014 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007015 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007016 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007017 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007018 (ParamTy->isIntegral() && ActTy->isIntegral() &&
7019 ParamTy->isSigned() == ActTy->isSigned() &&
7020 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7021 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007022 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007023 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007024 }
7025
7026 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7027 Callee->isExternal())
7028 return false; // Do not delete arguments unless we have a function body...
7029
7030 // Okay, we decided that this is a safe thing to do: go ahead and start
7031 // inserting cast instructions as necessary...
7032 std::vector<Value*> Args;
7033 Args.reserve(NumActualArgs);
7034
7035 AI = CS.arg_begin();
7036 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7037 const Type *ParamTy = FT->getParamType(i);
7038 if ((*AI)->getType() == ParamTy) {
7039 Args.push_back(*AI);
7040 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007041 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
7042 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007043 }
7044 }
7045
7046 // If the function takes more arguments than the call was taking, add them
7047 // now...
7048 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7049 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7050
7051 // If we are removing arguments to the function, emit an obnoxious warning...
7052 if (FT->getNumParams() < NumActualArgs)
7053 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007054 cerr << "WARNING: While resolving call to function '"
7055 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007056 } else {
7057 // Add all of the arguments in their promoted form to the arg list...
7058 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7059 const Type *PTy = getPromotedType((*AI)->getType());
7060 if (PTy != (*AI)->getType()) {
7061 // Must promote to pass through va_arg area!
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007062 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007063 InsertNewInstBefore(Cast, *Caller);
7064 Args.push_back(Cast);
7065 } else {
7066 Args.push_back(*AI);
7067 }
7068 }
7069 }
7070
7071 if (FT->getReturnType() == Type::VoidTy)
7072 Caller->setName(""); // Void type should not have a name...
7073
7074 Instruction *NC;
7075 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007076 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007077 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007078 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007079 } else {
7080 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007081 if (cast<CallInst>(Caller)->isTailCall())
7082 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007083 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007084 }
7085
7086 // Insert a cast of the return type as necessary...
7087 Value *NV = NC;
7088 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7089 if (NV->getType() != Type::VoidTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007090 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007091
7092 // If this is an invoke instruction, we should insert it after the first
7093 // non-phi, instruction in the normal successor block.
7094 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7095 BasicBlock::iterator I = II->getNormalDest()->begin();
7096 while (isa<PHINode>(I)) ++I;
7097 InsertNewInstBefore(NC, *I);
7098 } else {
7099 // Otherwise, it's a call, just insert cast right after the call instr
7100 InsertNewInstBefore(NC, *Caller);
7101 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007102 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007103 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007104 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007105 }
7106 }
7107
7108 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7109 Caller->replaceAllUsesWith(NV);
7110 Caller->getParent()->getInstList().erase(Caller);
7111 removeFromWorkList(Caller);
7112 return true;
7113}
7114
Chris Lattnercadac0c2006-11-01 04:51:18 +00007115/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7116/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7117/// and a single binop.
7118Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7119 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007120 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7121 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007122 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007123 Value *LHSVal = FirstInst->getOperand(0);
7124 Value *RHSVal = FirstInst->getOperand(1);
7125
7126 const Type *LHSType = LHSVal->getType();
7127 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007128
7129 // Scan to see if all operands are the same opcode, all have one use, and all
7130 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007131 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007132 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007133 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7134 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007135 // types or GEP's with different index types.
7136 I->getOperand(0)->getType() != LHSType ||
7137 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007138 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007139
7140 // Keep track of which operand needs a phi node.
7141 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7142 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007143 }
7144
Chris Lattner4f218d52006-11-08 19:42:28 +00007145 // Otherwise, this is safe to transform, determine if it is profitable.
7146
7147 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7148 // Indexes are often folded into load/store instructions, so we don't want to
7149 // hide them behind a phi.
7150 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7151 return 0;
7152
Chris Lattnercadac0c2006-11-01 04:51:18 +00007153 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007154 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007155 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007156 if (LHSVal == 0) {
7157 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7158 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7159 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007160 InsertNewInstBefore(NewLHS, PN);
7161 LHSVal = NewLHS;
7162 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007163
7164 if (RHSVal == 0) {
7165 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7166 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7167 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007168 InsertNewInstBefore(NewRHS, PN);
7169 RHSVal = NewRHS;
7170 }
7171
Chris Lattnercd62f112006-11-08 19:29:23 +00007172 // Add all operands to the new PHIs.
7173 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7174 if (NewLHS) {
7175 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7176 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7177 }
7178 if (NewRHS) {
7179 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7180 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7181 }
7182 }
7183
Chris Lattnercadac0c2006-11-01 04:51:18 +00007184 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007185 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7186 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7187 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7188 else {
7189 assert(isa<GetElementPtrInst>(FirstInst));
7190 return new GetElementPtrInst(LHSVal, RHSVal);
7191 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007192}
7193
Chris Lattner14f82c72006-11-01 07:13:54 +00007194/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7195/// of the block that defines it. This means that it must be obvious the value
7196/// of the load is not changed from the point of the load to the end of the
7197/// block it is in.
7198static bool isSafeToSinkLoad(LoadInst *L) {
7199 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7200
7201 for (++BBI; BBI != E; ++BBI)
7202 if (BBI->mayWriteToMemory())
7203 return false;
7204 return true;
7205}
7206
Chris Lattner970c33a2003-06-19 17:00:31 +00007207
Chris Lattner7515cab2004-11-14 19:13:23 +00007208// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7209// operator and they all are only used by the PHI, PHI together their
7210// inputs, and do the operation once, to the result of the PHI.
7211Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7212 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7213
7214 // Scan the instruction, looking for input operations that can be folded away.
7215 // If all input operands to the phi are the same instruction (e.g. a cast from
7216 // the same type or "+42") we can pull the operation through the PHI, reducing
7217 // code size and simplifying code.
7218 Constant *ConstantOp = 0;
7219 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007220 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007221 if (isa<CastInst>(FirstInst)) {
7222 CastSrcTy = FirstInst->getOperand(0)->getType();
7223 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007224 // Can fold binop or shift here if the RHS is a constant, otherwise call
7225 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007226 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007227 if (ConstantOp == 0)
7228 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007229 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7230 isVolatile = LI->isVolatile();
7231 // We can't sink the load if the loaded value could be modified between the
7232 // load and the PHI.
7233 if (LI->getParent() != PN.getIncomingBlock(0) ||
7234 !isSafeToSinkLoad(LI))
7235 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007236 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007237 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007238 return FoldPHIArgBinOpIntoPHI(PN);
7239 // Can't handle general GEPs yet.
7240 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007241 } else {
7242 return 0; // Cannot fold this operation.
7243 }
7244
7245 // Check to see if all arguments are the same operation.
7246 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7247 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7248 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7249 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7250 return 0;
7251 if (CastSrcTy) {
7252 if (I->getOperand(0)->getType() != CastSrcTy)
7253 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007254 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7255 // We can't sink the load if the loaded value could be modified between the
7256 // load and the PHI.
7257 if (LI->isVolatile() != isVolatile ||
7258 LI->getParent() != PN.getIncomingBlock(i) ||
7259 !isSafeToSinkLoad(LI))
7260 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007261 } else if (I->getOperand(1) != ConstantOp) {
7262 return 0;
7263 }
7264 }
7265
7266 // Okay, they are all the same operation. Create a new PHI node of the
7267 // correct type, and PHI together all of the LHS's of the instructions.
7268 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7269 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007270 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007271
7272 Value *InVal = FirstInst->getOperand(0);
7273 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007274
7275 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007276 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7277 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7278 if (NewInVal != InVal)
7279 InVal = 0;
7280 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7281 }
7282
7283 Value *PhiVal;
7284 if (InVal) {
7285 // The new PHI unions all of the same values together. This is really
7286 // common, so we handle it intelligently here for compile-time speed.
7287 PhiVal = InVal;
7288 delete NewPN;
7289 } else {
7290 InsertNewInstBefore(NewPN, PN);
7291 PhiVal = NewPN;
7292 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007293
Chris Lattner7515cab2004-11-14 19:13:23 +00007294 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007295 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7296 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007297 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007298 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007299 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007300 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007301 else
7302 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007303 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007304}
Chris Lattner48a44f72002-05-02 17:06:02 +00007305
Chris Lattner71536432005-01-17 05:10:15 +00007306/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7307/// that is dead.
7308static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7309 if (PN->use_empty()) return true;
7310 if (!PN->hasOneUse()) return false;
7311
7312 // Remember this node, and if we find the cycle, return.
7313 if (!PotentiallyDeadPHIs.insert(PN).second)
7314 return true;
7315
7316 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7317 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007318
Chris Lattner71536432005-01-17 05:10:15 +00007319 return false;
7320}
7321
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007322// PHINode simplification
7323//
Chris Lattner113f4f42002-06-25 16:13:24 +00007324Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007325 // If LCSSA is around, don't mess with Phi nodes
7326 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007327
Owen Andersonae8aa642006-07-10 22:03:18 +00007328 if (Value *V = PN.hasConstantValue())
7329 return ReplaceInstUsesWith(PN, V);
7330
Owen Andersonae8aa642006-07-10 22:03:18 +00007331 // If all PHI operands are the same operation, pull them through the PHI,
7332 // reducing code size.
7333 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7334 PN.getIncomingValue(0)->hasOneUse())
7335 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7336 return Result;
7337
7338 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7339 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7340 // PHI)... break the cycle.
7341 if (PN.hasOneUse())
7342 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7343 std::set<PHINode*> PotentiallyDeadPHIs;
7344 PotentiallyDeadPHIs.insert(&PN);
7345 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7346 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7347 }
7348
Chris Lattner91daeb52003-12-19 05:58:40 +00007349 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007350}
7351
Reid Spencer13bc5d72006-12-12 09:18:51 +00007352static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7353 Instruction *InsertPoint,
7354 InstCombiner *IC) {
7355 unsigned PtrSize = IC->getTargetData().getPointerSize();
7356 unsigned VTySize = V->getType()->getPrimitiveSize();
7357 // We must cast correctly to the pointer type. Ensure that we
7358 // sign extend the integer value if it is smaller as this is
7359 // used for address computation.
7360 Instruction::CastOps opcode =
7361 (VTySize < PtrSize ? Instruction::SExt :
7362 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7363 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007364}
7365
Chris Lattner48a44f72002-05-02 17:06:02 +00007366
Chris Lattner113f4f42002-06-25 16:13:24 +00007367Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007368 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007369 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007370 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007371 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007372 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007373
Chris Lattner81a7a232004-10-16 18:11:37 +00007374 if (isa<UndefValue>(GEP.getOperand(0)))
7375 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7376
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007377 bool HasZeroPointerIndex = false;
7378 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7379 HasZeroPointerIndex = C->isNullValue();
7380
7381 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007382 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007383
Chris Lattner69193f92004-04-05 01:30:19 +00007384 // Eliminate unneeded casts for indices.
7385 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007386 gep_type_iterator GTI = gep_type_begin(GEP);
7387 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7388 if (isa<SequentialType>(*GTI)) {
7389 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7390 Value *Src = CI->getOperand(0);
7391 const Type *SrcTy = Src->getType();
7392 const Type *DestTy = CI->getType();
7393 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007394 if (SrcTy->getPrimitiveSizeInBits() ==
7395 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007396 // We can always eliminate a cast from ulong or long to the other.
7397 // We can always eliminate a cast from uint to int or the other on
7398 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007399 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007400 MadeChange = true;
7401 GEP.setOperand(i, Src);
7402 }
7403 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7404 SrcTy->getPrimitiveSize() == 4) {
7405 // We can always eliminate a cast from int to [u]long. We can
7406 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7407 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007408 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007409 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007410 MadeChange = true;
7411 GEP.setOperand(i, Src);
7412 }
Chris Lattner69193f92004-04-05 01:30:19 +00007413 }
7414 }
7415 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007416 // If we are using a wider index than needed for this platform, shrink it
7417 // to what we need. If the incoming value needs a cast instruction,
7418 // insert it. This explicit cast can make subsequent optimizations more
7419 // obvious.
7420 Value *Op = GEP.getOperand(i);
7421 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007422 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007423 GEP.setOperand(i, ConstantExpr::getTrunc(C,
Chris Lattner44d0b952004-07-20 01:48:15 +00007424 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007425 MadeChange = true;
7426 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007427 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7428 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007429 GEP.setOperand(i, Op);
7430 MadeChange = true;
7431 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007432
7433 // If this is a constant idx, make sure to canonicalize it to be a signed
7434 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007435 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7436 if (CUI->getType()->isUnsigned()) {
7437 GEP.setOperand(i,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007438 ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007439 MadeChange = true;
7440 }
Chris Lattner69193f92004-04-05 01:30:19 +00007441 }
7442 if (MadeChange) return &GEP;
7443
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007444 // Combine Indices - If the source pointer to this getelementptr instruction
7445 // is a getelementptr instruction, combine the indices of the two
7446 // getelementptr instructions into a single instruction.
7447 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007448 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007449 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007450 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007451
7452 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007453 // Note that if our source is a gep chain itself that we wait for that
7454 // chain to be resolved before we perform this transformation. This
7455 // avoids us creating a TON of code in some cases.
7456 //
7457 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7458 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7459 return 0; // Wait until our source is folded to completion.
7460
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007461 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007462
7463 // Find out whether the last index in the source GEP is a sequential idx.
7464 bool EndsWithSequential = false;
7465 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7466 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007467 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007468
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007469 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007470 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007471 // Replace: gep (gep %P, long B), long A, ...
7472 // With: T = long A+B; gep %P, T, ...
7473 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007474 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007475 if (SO1 == Constant::getNullValue(SO1->getType())) {
7476 Sum = GO1;
7477 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7478 Sum = SO1;
7479 } else {
7480 // If they aren't the same type, convert both to an integer of the
7481 // target's pointer size.
7482 if (SO1->getType() != GO1->getType()) {
7483 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007484 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007485 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007486 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007487 } else {
7488 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007489 if (SO1->getType()->getPrimitiveSize() == PS) {
7490 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007491 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007492
7493 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7494 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007495 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007496 } else {
7497 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007498 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7499 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007500 }
7501 }
7502 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007503 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7504 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7505 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007506 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7507 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007508 }
Chris Lattner69193f92004-04-05 01:30:19 +00007509 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007510
7511 // Recycle the GEP we already have if possible.
7512 if (SrcGEPOperands.size() == 2) {
7513 GEP.setOperand(0, SrcGEPOperands[0]);
7514 GEP.setOperand(1, Sum);
7515 return &GEP;
7516 } else {
7517 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7518 SrcGEPOperands.end()-1);
7519 Indices.push_back(Sum);
7520 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7521 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007522 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007523 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007524 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007525 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007526 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7527 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007528 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7529 }
7530
7531 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007532 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007533
Chris Lattner5f667a62004-05-07 22:09:22 +00007534 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007535 // GEP of global variable. If all of the indices for this GEP are
7536 // constants, we can promote this to a constexpr instead of an instruction.
7537
7538 // Scan for nonconstants...
7539 std::vector<Constant*> Indices;
7540 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7541 for (; I != E && isa<Constant>(*I); ++I)
7542 Indices.push_back(cast<Constant>(*I));
7543
7544 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007545 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007546
7547 // Replace all uses of the GEP with the new constexpr...
7548 return ReplaceInstUsesWith(GEP, CE);
7549 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007550 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007551 if (!isa<PointerType>(X->getType())) {
7552 // Not interesting. Source pointer must be a cast from pointer.
7553 } else if (HasZeroPointerIndex) {
7554 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7555 // into : GEP [10 x ubyte]* X, long 0, ...
7556 //
7557 // This occurs when the program declares an array extern like "int X[];"
7558 //
7559 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7560 const PointerType *XTy = cast<PointerType>(X->getType());
7561 if (const ArrayType *XATy =
7562 dyn_cast<ArrayType>(XTy->getElementType()))
7563 if (const ArrayType *CATy =
7564 dyn_cast<ArrayType>(CPTy->getElementType()))
7565 if (CATy->getElementType() == XATy->getElementType()) {
7566 // At this point, we know that the cast source type is a pointer
7567 // to an array of the same type as the destination pointer
7568 // array. Because the array type is never stepped over (there
7569 // is a leading zero) we can fold the cast into this GEP.
7570 GEP.setOperand(0, X);
7571 return &GEP;
7572 }
7573 } else if (GEP.getNumOperands() == 2) {
7574 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007575 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7576 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007577 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7578 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7579 if (isa<ArrayType>(SrcElTy) &&
7580 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7581 TD->getTypeSize(ResElTy)) {
7582 Value *V = InsertNewInstBefore(
7583 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7584 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007585 // V and GEP are both pointer types --> BitCast
7586 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007587 }
Chris Lattner2a893292005-09-13 18:36:04 +00007588
7589 // Transform things like:
7590 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7591 // (where tmp = 8*tmp2) into:
7592 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7593
7594 if (isa<ArrayType>(SrcElTy) &&
7595 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7596 uint64_t ArrayEltSize =
7597 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7598
7599 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7600 // allow either a mul, shift, or constant here.
7601 Value *NewIdx = 0;
7602 ConstantInt *Scale = 0;
7603 if (ArrayEltSize == 1) {
7604 NewIdx = GEP.getOperand(1);
7605 Scale = ConstantInt::get(NewIdx->getType(), 1);
7606 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007607 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007608 Scale = CI;
7609 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7610 if (Inst->getOpcode() == Instruction::Shl &&
7611 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007612 unsigned ShAmt =
7613 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007614 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007615 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007616 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007617 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007618 NewIdx = Inst->getOperand(0);
7619 } else if (Inst->getOpcode() == Instruction::Mul &&
7620 isa<ConstantInt>(Inst->getOperand(1))) {
7621 Scale = cast<ConstantInt>(Inst->getOperand(1));
7622 NewIdx = Inst->getOperand(0);
7623 }
7624 }
7625
7626 // If the index will be to exactly the right offset with the scale taken
7627 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007628 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007629 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007630 Scale = ConstantInt::get(Scale->getType(),
7631 Scale->getZExtValue() / ArrayEltSize);
7632 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007633 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7634 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007635 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7636 NewIdx = InsertNewInstBefore(Sc, GEP);
7637 }
7638
7639 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007640 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007641 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7642 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007643 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7644 // The NewGEP must be pointer typed, so must the old one -> BitCast
7645 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007646 }
7647 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007648 }
Chris Lattnerca081252001-12-14 16:52:21 +00007649 }
7650
Chris Lattnerca081252001-12-14 16:52:21 +00007651 return 0;
7652}
7653
Chris Lattner1085bdf2002-11-04 16:18:53 +00007654Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7655 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7656 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007657 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7658 const Type *NewTy =
7659 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007660 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007661
7662 // Create and insert the replacement instruction...
7663 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007664 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007665 else {
7666 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007667 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007668 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007669
7670 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007671
Chris Lattner1085bdf2002-11-04 16:18:53 +00007672 // Scan to the end of the allocation instructions, to skip over a block of
7673 // allocas if possible...
7674 //
7675 BasicBlock::iterator It = New;
7676 while (isa<AllocationInst>(*It)) ++It;
7677
7678 // Now that I is pointing to the first non-allocation-inst in the block,
7679 // insert our getelementptr instruction...
7680 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007681 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7682 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7683 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007684
7685 // Now make everything use the getelementptr instead of the original
7686 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007687 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007688 } else if (isa<UndefValue>(AI.getArraySize())) {
7689 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007690 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007691
7692 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7693 // Note that we only do this for alloca's, because malloc should allocate and
7694 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007695 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007696 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007697 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7698
Chris Lattner1085bdf2002-11-04 16:18:53 +00007699 return 0;
7700}
7701
Chris Lattner8427bff2003-12-07 01:24:23 +00007702Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7703 Value *Op = FI.getOperand(0);
7704
7705 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7706 if (CastInst *CI = dyn_cast<CastInst>(Op))
7707 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7708 FI.setOperand(0, CI->getOperand(0));
7709 return &FI;
7710 }
7711
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007712 // free undef -> unreachable.
7713 if (isa<UndefValue>(Op)) {
7714 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007715 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007716 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7717 return EraseInstFromFunction(FI);
7718 }
7719
Chris Lattnerf3a36602004-02-28 04:57:37 +00007720 // If we have 'free null' delete the instruction. This can happen in stl code
7721 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007722 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007723 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007724
Chris Lattner8427bff2003-12-07 01:24:23 +00007725 return 0;
7726}
7727
7728
Chris Lattner72684fe2005-01-31 05:51:45 +00007729/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007730static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7731 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007732 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007733
7734 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007735 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007736 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007737
Chris Lattnerebca4762006-04-02 05:37:12 +00007738 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7739 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007740 // If the source is an array, the code below will not succeed. Check to
7741 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7742 // constants.
7743 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7744 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7745 if (ASrcTy->getNumElements() != 0) {
7746 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7747 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7748 SrcTy = cast<PointerType>(CastOp->getType());
7749 SrcPTy = SrcTy->getElementType();
7750 }
7751
Chris Lattnerebca4762006-04-02 05:37:12 +00007752 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7753 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007754 // Do not allow turning this into a load of an integer, which is then
7755 // casted to a pointer, this pessimizes pointer analysis a lot.
7756 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007757 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007758 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007759
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007760 // Okay, we are casting from one integer or pointer type to another of
7761 // the same size. Instead of casting the pointer before the load, cast
7762 // the result of the loaded value.
7763 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7764 CI->getName(),
7765 LI.isVolatile()),LI);
7766 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007767 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007768 }
Chris Lattner35e24772004-07-13 01:49:43 +00007769 }
7770 }
7771 return 0;
7772}
7773
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007774/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007775/// from this value cannot trap. If it is not obviously safe to load from the
7776/// specified pointer, we do a quick local scan of the basic block containing
7777/// ScanFrom, to determine if the address is already accessed.
7778static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7779 // If it is an alloca or global variable, it is always safe to load from.
7780 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7781
7782 // Otherwise, be a little bit agressive by scanning the local block where we
7783 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007784 // from/to. If so, the previous load or store would have already trapped,
7785 // so there is no harm doing an extra load (also, CSE will later eliminate
7786 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007787 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7788
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007789 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007790 --BBI;
7791
7792 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7793 if (LI->getOperand(0) == V) return true;
7794 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7795 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007796
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007797 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007798 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007799}
7800
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007801Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7802 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007803
Chris Lattnera9d84e32005-05-01 04:24:53 +00007804 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007805 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007806 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7807 return Res;
7808
7809 // None of the following transforms are legal for volatile loads.
7810 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007811
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007812 if (&LI.getParent()->front() != &LI) {
7813 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007814 // If the instruction immediately before this is a store to the same
7815 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007816 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7817 if (SI->getOperand(1) == LI.getOperand(0))
7818 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007819 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7820 if (LIB->getOperand(0) == LI.getOperand(0))
7821 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007822 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007823
7824 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7825 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7826 isa<UndefValue>(GEPI->getOperand(0))) {
7827 // Insert a new store to null instruction before the load to indicate
7828 // that this code is not reachable. We do this instead of inserting
7829 // an unreachable instruction directly because we cannot modify the
7830 // CFG.
7831 new StoreInst(UndefValue::get(LI.getType()),
7832 Constant::getNullValue(Op->getType()), &LI);
7833 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7834 }
7835
Chris Lattner81a7a232004-10-16 18:11:37 +00007836 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007837 // load null/undef -> undef
7838 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007839 // Insert a new store to null instruction before the load to indicate that
7840 // this code is not reachable. We do this instead of inserting an
7841 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007842 new StoreInst(UndefValue::get(LI.getType()),
7843 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007844 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007845 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007846
Chris Lattner81a7a232004-10-16 18:11:37 +00007847 // Instcombine load (constant global) into the value loaded.
7848 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7849 if (GV->isConstant() && !GV->isExternal())
7850 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007851
Chris Lattner81a7a232004-10-16 18:11:37 +00007852 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7853 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7854 if (CE->getOpcode() == Instruction::GetElementPtr) {
7855 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7856 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007857 if (Constant *V =
7858 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007859 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007860 if (CE->getOperand(0)->isNullValue()) {
7861 // Insert a new store to null instruction before the load to indicate
7862 // that this code is not reachable. We do this instead of inserting
7863 // an unreachable instruction directly because we cannot modify the
7864 // CFG.
7865 new StoreInst(UndefValue::get(LI.getType()),
7866 Constant::getNullValue(Op->getType()), &LI);
7867 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7868 }
7869
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007870 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00007871 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7872 return Res;
7873 }
7874 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007875
Chris Lattnera9d84e32005-05-01 04:24:53 +00007876 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007877 // Change select and PHI nodes to select values instead of addresses: this
7878 // helps alias analysis out a lot, allows many others simplifications, and
7879 // exposes redundancy in the code.
7880 //
7881 // Note that we cannot do the transformation unless we know that the
7882 // introduced loads cannot trap! Something like this is valid as long as
7883 // the condition is always false: load (select bool %C, int* null, int* %G),
7884 // but it would not be valid if we transformed it to load from null
7885 // unconditionally.
7886 //
7887 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7888 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007889 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7890 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007891 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007892 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007893 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007894 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007895 return new SelectInst(SI->getCondition(), V1, V2);
7896 }
7897
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007898 // load (select (cond, null, P)) -> load P
7899 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7900 if (C->isNullValue()) {
7901 LI.setOperand(0, SI->getOperand(2));
7902 return &LI;
7903 }
7904
7905 // load (select (cond, P, null)) -> load P
7906 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7907 if (C->isNullValue()) {
7908 LI.setOperand(0, SI->getOperand(1));
7909 return &LI;
7910 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007911 }
7912 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007913 return 0;
7914}
7915
Chris Lattner72684fe2005-01-31 05:51:45 +00007916/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7917/// when possible.
7918static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7919 User *CI = cast<User>(SI.getOperand(1));
7920 Value *CastOp = CI->getOperand(0);
7921
7922 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7923 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7924 const Type *SrcPTy = SrcTy->getElementType();
7925
7926 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7927 // If the source is an array, the code below will not succeed. Check to
7928 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7929 // constants.
7930 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7931 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7932 if (ASrcTy->getNumElements() != 0) {
7933 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7934 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7935 SrcTy = cast<PointerType>(CastOp->getType());
7936 SrcPTy = SrcTy->getElementType();
7937 }
7938
7939 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007940 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007941 IC.getTargetData().getTypeSize(DestPTy)) {
7942
7943 // Okay, we are casting from one integer or pointer type to another of
7944 // the same size. Instead of casting the pointer before the store, cast
7945 // the value to be stored.
7946 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007947 Instruction::CastOps opcode = Instruction::BitCast;
7948 Value *SIOp0 = SI.getOperand(0);
7949 if (SrcPTy->getTypeID() == Type::PointerTyID) {
7950 if (SIOp0->getType()->isIntegral())
7951 opcode = Instruction::IntToPtr;
7952 } else if (SrcPTy->isIntegral()) {
7953 if (SIOp0->getType()->getTypeID() == Type::PointerTyID)
7954 opcode = Instruction::PtrToInt;
7955 }
7956 if (Constant *C = dyn_cast<Constant>(SIOp0))
7957 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00007958 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007959 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007960 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00007961 return new StoreInst(NewCast, CastOp);
7962 }
7963 }
7964 }
7965 return 0;
7966}
7967
Chris Lattner31f486c2005-01-31 05:36:43 +00007968Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7969 Value *Val = SI.getOperand(0);
7970 Value *Ptr = SI.getOperand(1);
7971
7972 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007973 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007974 ++NumCombined;
7975 return 0;
7976 }
7977
Chris Lattner5997cf92006-02-08 03:25:32 +00007978 // Do really simple DSE, to catch cases where there are several consequtive
7979 // stores to the same location, separated by a few arithmetic operations. This
7980 // situation often occurs with bitfield accesses.
7981 BasicBlock::iterator BBI = &SI;
7982 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7983 --ScanInsts) {
7984 --BBI;
7985
7986 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7987 // Prev store isn't volatile, and stores to the same location?
7988 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7989 ++NumDeadStore;
7990 ++BBI;
7991 EraseInstFromFunction(*PrevSI);
7992 continue;
7993 }
7994 break;
7995 }
7996
Chris Lattnerdab43b22006-05-26 19:19:20 +00007997 // If this is a load, we have to stop. However, if the loaded value is from
7998 // the pointer we're loading and is producing the pointer we're storing,
7999 // then *this* store is dead (X = load P; store X -> P).
8000 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8001 if (LI == Val && LI->getOperand(0) == Ptr) {
8002 EraseInstFromFunction(SI);
8003 ++NumCombined;
8004 return 0;
8005 }
8006 // Otherwise, this is a load from some other location. Stores before it
8007 // may not be dead.
8008 break;
8009 }
8010
Chris Lattner5997cf92006-02-08 03:25:32 +00008011 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008012 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008013 break;
8014 }
8015
8016
8017 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008018
8019 // store X, null -> turns into 'unreachable' in SimplifyCFG
8020 if (isa<ConstantPointerNull>(Ptr)) {
8021 if (!isa<UndefValue>(Val)) {
8022 SI.setOperand(0, UndefValue::get(Val->getType()));
8023 if (Instruction *U = dyn_cast<Instruction>(Val))
8024 WorkList.push_back(U); // Dropped a use.
8025 ++NumCombined;
8026 }
8027 return 0; // Do not modify these!
8028 }
8029
8030 // store undef, Ptr -> noop
8031 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008032 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008033 ++NumCombined;
8034 return 0;
8035 }
8036
Chris Lattner72684fe2005-01-31 05:51:45 +00008037 // If the pointer destination is a cast, see if we can fold the cast into the
8038 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008039 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008040 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8041 return Res;
8042 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008043 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008044 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8045 return Res;
8046
Chris Lattner219175c2005-09-12 23:23:25 +00008047
8048 // If this store is the last instruction in the basic block, and if the block
8049 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008050 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008051 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8052 if (BI->isUnconditional()) {
8053 // Check to see if the successor block has exactly two incoming edges. If
8054 // so, see if the other predecessor contains a store to the same location.
8055 // if so, insert a PHI node (if needed) and move the stores down.
8056 BasicBlock *Dest = BI->getSuccessor(0);
8057
8058 pred_iterator PI = pred_begin(Dest);
8059 BasicBlock *Other = 0;
8060 if (*PI != BI->getParent())
8061 Other = *PI;
8062 ++PI;
8063 if (PI != pred_end(Dest)) {
8064 if (*PI != BI->getParent())
8065 if (Other)
8066 Other = 0;
8067 else
8068 Other = *PI;
8069 if (++PI != pred_end(Dest))
8070 Other = 0;
8071 }
8072 if (Other) { // If only one other pred...
8073 BBI = Other->getTerminator();
8074 // Make sure this other block ends in an unconditional branch and that
8075 // there is an instruction before the branch.
8076 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8077 BBI != Other->begin()) {
8078 --BBI;
8079 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8080
8081 // If this instruction is a store to the same location.
8082 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8083 // Okay, we know we can perform this transformation. Insert a PHI
8084 // node now if we need it.
8085 Value *MergedVal = OtherStore->getOperand(0);
8086 if (MergedVal != SI.getOperand(0)) {
8087 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8088 PN->reserveOperandSpace(2);
8089 PN->addIncoming(SI.getOperand(0), SI.getParent());
8090 PN->addIncoming(OtherStore->getOperand(0), Other);
8091 MergedVal = InsertNewInstBefore(PN, Dest->front());
8092 }
8093
8094 // Advance to a place where it is safe to insert the new store and
8095 // insert it.
8096 BBI = Dest->begin();
8097 while (isa<PHINode>(BBI)) ++BBI;
8098 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8099 OtherStore->isVolatile()), *BBI);
8100
8101 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008102 EraseInstFromFunction(SI);
8103 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008104 ++NumCombined;
8105 return 0;
8106 }
8107 }
8108 }
8109 }
8110
Chris Lattner31f486c2005-01-31 05:36:43 +00008111 return 0;
8112}
8113
8114
Chris Lattner9eef8a72003-06-04 04:46:00 +00008115Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8116 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008117 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008118 BasicBlock *TrueDest;
8119 BasicBlock *FalseDest;
8120 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8121 !isa<Constant>(X)) {
8122 // Swap Destinations and condition...
8123 BI.setCondition(X);
8124 BI.setSuccessor(0, FalseDest);
8125 BI.setSuccessor(1, TrueDest);
8126 return &BI;
8127 }
8128
8129 // Cannonicalize setne -> seteq
8130 Instruction::BinaryOps Op; Value *Y;
8131 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8132 TrueDest, FalseDest)))
8133 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8134 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8135 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8136 std::string Name = I->getName(); I->setName("");
8137 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8138 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008139 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008140 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008141 BI.setSuccessor(0, FalseDest);
8142 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008143 removeFromWorkList(I);
8144 I->getParent()->getInstList().erase(I);
8145 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008146 return &BI;
8147 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008148
Chris Lattner9eef8a72003-06-04 04:46:00 +00008149 return 0;
8150}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008151
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008152Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8153 Value *Cond = SI.getCondition();
8154 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8155 if (I->getOpcode() == Instruction::Add)
8156 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8157 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8158 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008159 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008160 AddRHS));
8161 SI.setOperand(0, I->getOperand(0));
8162 WorkList.push_back(I);
8163 return &SI;
8164 }
8165 }
8166 return 0;
8167}
8168
Chris Lattner6bc98652006-03-05 00:22:33 +00008169/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8170/// is to leave as a vector operation.
8171static bool CheapToScalarize(Value *V, bool isConstant) {
8172 if (isa<ConstantAggregateZero>(V))
8173 return true;
8174 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8175 if (isConstant) return true;
8176 // If all elts are the same, we can extract.
8177 Constant *Op0 = C->getOperand(0);
8178 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8179 if (C->getOperand(i) != Op0)
8180 return false;
8181 return true;
8182 }
8183 Instruction *I = dyn_cast<Instruction>(V);
8184 if (!I) return false;
8185
8186 // Insert element gets simplified to the inserted element or is deleted if
8187 // this is constant idx extract element and its a constant idx insertelt.
8188 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8189 isa<ConstantInt>(I->getOperand(2)))
8190 return true;
8191 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8192 return true;
8193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8194 if (BO->hasOneUse() &&
8195 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8196 CheapToScalarize(BO->getOperand(1), isConstant)))
8197 return true;
8198
8199 return false;
8200}
8201
Chris Lattner12249be2006-05-25 23:48:38 +00008202/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8203/// elements into values that are larger than the #elts in the input.
8204static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8205 unsigned NElts = SVI->getType()->getNumElements();
8206 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8207 return std::vector<unsigned>(NElts, 0);
8208 if (isa<UndefValue>(SVI->getOperand(2)))
8209 return std::vector<unsigned>(NElts, 2*NElts);
8210
8211 std::vector<unsigned> Result;
8212 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8213 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8214 if (isa<UndefValue>(CP->getOperand(i)))
8215 Result.push_back(NElts*2); // undef -> 8
8216 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008217 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008218 return Result;
8219}
8220
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008221/// FindScalarElement - Given a vector and an element number, see if the scalar
8222/// value is already around as a register, for example if it were inserted then
8223/// extracted from the vector.
8224static Value *FindScalarElement(Value *V, unsigned EltNo) {
8225 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8226 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008227 unsigned Width = PTy->getNumElements();
8228 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008229 return UndefValue::get(PTy->getElementType());
8230
8231 if (isa<UndefValue>(V))
8232 return UndefValue::get(PTy->getElementType());
8233 else if (isa<ConstantAggregateZero>(V))
8234 return Constant::getNullValue(PTy->getElementType());
8235 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8236 return CP->getOperand(EltNo);
8237 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8238 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008239 if (!isa<ConstantInt>(III->getOperand(2)))
8240 return 0;
8241 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008242
8243 // If this is an insert to the element we are looking for, return the
8244 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008245 if (EltNo == IIElt)
8246 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008247
8248 // Otherwise, the insertelement doesn't modify the value, recurse on its
8249 // vector input.
8250 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008251 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008252 unsigned InEl = getShuffleMask(SVI)[EltNo];
8253 if (InEl < Width)
8254 return FindScalarElement(SVI->getOperand(0), InEl);
8255 else if (InEl < Width*2)
8256 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8257 else
8258 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008259 }
8260
8261 // Otherwise, we don't know.
8262 return 0;
8263}
8264
Robert Bocchinoa8352962006-01-13 22:48:06 +00008265Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008266
Chris Lattner92346c32006-03-31 18:25:14 +00008267 // If packed val is undef, replace extract with scalar undef.
8268 if (isa<UndefValue>(EI.getOperand(0)))
8269 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8270
8271 // If packed val is constant 0, replace extract with scalar 0.
8272 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8273 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8274
Robert Bocchinoa8352962006-01-13 22:48:06 +00008275 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8276 // If packed val is constant with uniform operands, replace EI
8277 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008278 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008279 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008280 if (C->getOperand(i) != op0) {
8281 op0 = 0;
8282 break;
8283 }
8284 if (op0)
8285 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008286 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008287
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008288 // If extracting a specified index from the vector, see if we can recursively
8289 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008290 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008291 // This instruction only demands the single element from the input vector.
8292 // If the input vector has a single use, simplify it based on this use
8293 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008294 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008295 if (EI.getOperand(0)->hasOneUse()) {
8296 uint64_t UndefElts;
8297 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008298 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008299 UndefElts)) {
8300 EI.setOperand(0, V);
8301 return &EI;
8302 }
8303 }
8304
Reid Spencere0fc4df2006-10-20 07:07:24 +00008305 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008306 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008307 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008308
Chris Lattner83f65782006-05-25 22:53:38 +00008309 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008310 if (I->hasOneUse()) {
8311 // Push extractelement into predecessor operation if legal and
8312 // profitable to do so
8313 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008314 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8315 if (CheapToScalarize(BO, isConstantElt)) {
8316 ExtractElementInst *newEI0 =
8317 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8318 EI.getName()+".lhs");
8319 ExtractElementInst *newEI1 =
8320 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8321 EI.getName()+".rhs");
8322 InsertNewInstBefore(newEI0, EI);
8323 InsertNewInstBefore(newEI1, EI);
8324 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8325 }
Reid Spencerde46e482006-11-02 20:25:50 +00008326 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008327 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008328 PointerType::get(EI.getType()), EI);
8329 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008330 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008331 InsertNewInstBefore(GEP, EI);
8332 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008333 }
8334 }
8335 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8336 // Extracting the inserted element?
8337 if (IE->getOperand(2) == EI.getOperand(1))
8338 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8339 // If the inserted and extracted elements are constants, they must not
8340 // be the same value, extract from the pre-inserted value instead.
8341 if (isa<Constant>(IE->getOperand(2)) &&
8342 isa<Constant>(EI.getOperand(1))) {
8343 AddUsesToWorkList(EI);
8344 EI.setOperand(0, IE->getOperand(0));
8345 return &EI;
8346 }
8347 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8348 // If this is extracting an element from a shufflevector, figure out where
8349 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008350 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8351 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008352 Value *Src;
8353 if (SrcIdx < SVI->getType()->getNumElements())
8354 Src = SVI->getOperand(0);
8355 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8356 SrcIdx -= SVI->getType()->getNumElements();
8357 Src = SVI->getOperand(1);
8358 } else {
8359 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008360 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008361 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008362 }
8363 }
Chris Lattner83f65782006-05-25 22:53:38 +00008364 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008365 return 0;
8366}
8367
Chris Lattner90951862006-04-16 00:51:47 +00008368/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8369/// elements from either LHS or RHS, return the shuffle mask and true.
8370/// Otherwise, return false.
8371static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8372 std::vector<Constant*> &Mask) {
8373 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8374 "Invalid CollectSingleShuffleElements");
8375 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8376
8377 if (isa<UndefValue>(V)) {
8378 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8379 return true;
8380 } else if (V == LHS) {
8381 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008382 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008383 return true;
8384 } else if (V == RHS) {
8385 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008386 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008387 return true;
8388 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8389 // If this is an insert of an extract from some other vector, include it.
8390 Value *VecOp = IEI->getOperand(0);
8391 Value *ScalarOp = IEI->getOperand(1);
8392 Value *IdxOp = IEI->getOperand(2);
8393
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008394 if (!isa<ConstantInt>(IdxOp))
8395 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008396 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008397
8398 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8399 // Okay, we can handle this if the vector we are insertinting into is
8400 // transitively ok.
8401 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8402 // If so, update the mask to reflect the inserted undef.
8403 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8404 return true;
8405 }
8406 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8407 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008408 EI->getOperand(0)->getType() == V->getType()) {
8409 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008410 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008411
8412 // This must be extracting from either LHS or RHS.
8413 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8414 // Okay, we can handle this if the vector we are insertinting into is
8415 // transitively ok.
8416 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8417 // If so, update the mask to reflect the inserted value.
8418 if (EI->getOperand(0) == LHS) {
8419 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008420 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008421 } else {
8422 assert(EI->getOperand(0) == RHS);
8423 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008424 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008425
8426 }
8427 return true;
8428 }
8429 }
8430 }
8431 }
8432 }
8433 // TODO: Handle shufflevector here!
8434
8435 return false;
8436}
8437
8438/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8439/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8440/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008441static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008442 Value *&RHS) {
8443 assert(isa<PackedType>(V->getType()) &&
8444 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008445 "Invalid shuffle!");
8446 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8447
8448 if (isa<UndefValue>(V)) {
8449 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8450 return V;
8451 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008452 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008453 return V;
8454 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8455 // If this is an insert of an extract from some other vector, include it.
8456 Value *VecOp = IEI->getOperand(0);
8457 Value *ScalarOp = IEI->getOperand(1);
8458 Value *IdxOp = IEI->getOperand(2);
8459
8460 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8461 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8462 EI->getOperand(0)->getType() == V->getType()) {
8463 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008464 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8465 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008466
8467 // Either the extracted from or inserted into vector must be RHSVec,
8468 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008469 if (EI->getOperand(0) == RHS || RHS == 0) {
8470 RHS = EI->getOperand(0);
8471 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008472 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008473 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008474 return V;
8475 }
8476
Chris Lattner90951862006-04-16 00:51:47 +00008477 if (VecOp == RHS) {
8478 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008479 // Everything but the extracted element is replaced with the RHS.
8480 for (unsigned i = 0; i != NumElts; ++i) {
8481 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008482 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008483 }
8484 return V;
8485 }
Chris Lattner90951862006-04-16 00:51:47 +00008486
8487 // If this insertelement is a chain that comes from exactly these two
8488 // vectors, return the vector and the effective shuffle.
8489 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8490 return EI->getOperand(0);
8491
Chris Lattner39fac442006-04-15 01:39:45 +00008492 }
8493 }
8494 }
Chris Lattner90951862006-04-16 00:51:47 +00008495 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008496
8497 // Otherwise, can't do anything fancy. Return an identity vector.
8498 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008499 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008500 return V;
8501}
8502
8503Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8504 Value *VecOp = IE.getOperand(0);
8505 Value *ScalarOp = IE.getOperand(1);
8506 Value *IdxOp = IE.getOperand(2);
8507
8508 // If the inserted element was extracted from some other vector, and if the
8509 // indexes are constant, try to turn this into a shufflevector operation.
8510 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8511 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8512 EI->getOperand(0)->getType() == IE.getType()) {
8513 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008514 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8515 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008516
8517 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8518 return ReplaceInstUsesWith(IE, VecOp);
8519
8520 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8521 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8522
8523 // If we are extracting a value from a vector, then inserting it right
8524 // back into the same place, just use the input vector.
8525 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8526 return ReplaceInstUsesWith(IE, VecOp);
8527
8528 // We could theoretically do this for ANY input. However, doing so could
8529 // turn chains of insertelement instructions into a chain of shufflevector
8530 // instructions, and right now we do not merge shufflevectors. As such,
8531 // only do this in a situation where it is clear that there is benefit.
8532 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8533 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8534 // the values of VecOp, except then one read from EIOp0.
8535 // Build a new shuffle mask.
8536 std::vector<Constant*> Mask;
8537 if (isa<UndefValue>(VecOp))
8538 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8539 else {
8540 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008541 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008542 NumVectorElts));
8543 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008544 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008545 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8546 ConstantPacked::get(Mask));
8547 }
8548
8549 // If this insertelement isn't used by some other insertelement, turn it
8550 // (and any insertelements it points to), into one big shuffle.
8551 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8552 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008553 Value *RHS = 0;
8554 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8555 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8556 // We now have a shuffle of LHS, RHS, Mask.
8557 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008558 }
8559 }
8560 }
8561
8562 return 0;
8563}
8564
8565
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008566Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8567 Value *LHS = SVI.getOperand(0);
8568 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008569 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008570
8571 bool MadeChange = false;
8572
Chris Lattner2deeaea2006-10-05 06:55:50 +00008573 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008574 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008575 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8576
Chris Lattner39fac442006-04-15 01:39:45 +00008577 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8578 // the undef, change them to undefs.
8579
Chris Lattner12249be2006-05-25 23:48:38 +00008580 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8581 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8582 if (LHS == RHS || isa<UndefValue>(LHS)) {
8583 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008584 // shuffle(undef,undef,mask) -> undef.
8585 return ReplaceInstUsesWith(SVI, LHS);
8586 }
8587
Chris Lattner12249be2006-05-25 23:48:38 +00008588 // Remap any references to RHS to use LHS.
8589 std::vector<Constant*> Elts;
8590 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008591 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008592 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008593 else {
8594 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8595 (Mask[i] < e && isa<UndefValue>(LHS)))
8596 Mask[i] = 2*e; // Turn into undef.
8597 else
8598 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008599 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008600 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008601 }
Chris Lattner12249be2006-05-25 23:48:38 +00008602 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008603 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008604 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008605 LHS = SVI.getOperand(0);
8606 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008607 MadeChange = true;
8608 }
8609
Chris Lattner0e477162006-05-26 00:29:06 +00008610 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008611 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008612
Chris Lattner12249be2006-05-25 23:48:38 +00008613 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8614 if (Mask[i] >= e*2) continue; // Ignore undef values.
8615 // Is this an identity shuffle of the LHS value?
8616 isLHSID &= (Mask[i] == i);
8617
8618 // Is this an identity shuffle of the RHS value?
8619 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008620 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008621
Chris Lattner12249be2006-05-25 23:48:38 +00008622 // Eliminate identity shuffles.
8623 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8624 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008625
Chris Lattner0e477162006-05-26 00:29:06 +00008626 // If the LHS is a shufflevector itself, see if we can combine it with this
8627 // one without producing an unusual shuffle. Here we are really conservative:
8628 // we are absolutely afraid of producing a shuffle mask not in the input
8629 // program, because the code gen may not be smart enough to turn a merged
8630 // shuffle into two specific shuffles: it may produce worse code. As such,
8631 // we only merge two shuffles if the result is one of the two input shuffle
8632 // masks. In this case, merging the shuffles just removes one instruction,
8633 // which we know is safe. This is good for things like turning:
8634 // (splat(splat)) -> splat.
8635 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8636 if (isa<UndefValue>(RHS)) {
8637 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8638
8639 std::vector<unsigned> NewMask;
8640 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8641 if (Mask[i] >= 2*e)
8642 NewMask.push_back(2*e);
8643 else
8644 NewMask.push_back(LHSMask[Mask[i]]);
8645
8646 // If the result mask is equal to the src shuffle or this shuffle mask, do
8647 // the replacement.
8648 if (NewMask == LHSMask || NewMask == Mask) {
8649 std::vector<Constant*> Elts;
8650 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8651 if (NewMask[i] >= e*2) {
8652 Elts.push_back(UndefValue::get(Type::UIntTy));
8653 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008654 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008655 }
8656 }
8657 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8658 LHSSVI->getOperand(1),
8659 ConstantPacked::get(Elts));
8660 }
8661 }
8662 }
8663
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008664 return MadeChange ? &SVI : 0;
8665}
8666
8667
Robert Bocchinoa8352962006-01-13 22:48:06 +00008668
Chris Lattner99f48c62002-09-02 04:59:56 +00008669void InstCombiner::removeFromWorkList(Instruction *I) {
8670 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8671 WorkList.end());
8672}
8673
Chris Lattner39c98bb2004-12-08 23:43:58 +00008674
8675/// TryToSinkInstruction - Try to move the specified instruction from its
8676/// current block into the beginning of DestBlock, which can only happen if it's
8677/// safe to move the instruction past all of the instructions between it and the
8678/// end of its block.
8679static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8680 assert(I->hasOneUse() && "Invariants didn't hold!");
8681
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008682 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8683 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008684
Chris Lattner39c98bb2004-12-08 23:43:58 +00008685 // Do not sink alloca instructions out of the entry block.
8686 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8687 return false;
8688
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008689 // We can only sink load instructions if there is nothing between the load and
8690 // the end of block that could change the value.
8691 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008692 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8693 Scan != E; ++Scan)
8694 if (Scan->mayWriteToMemory())
8695 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008696 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008697
8698 BasicBlock::iterator InsertPos = DestBlock->begin();
8699 while (isa<PHINode>(InsertPos)) ++InsertPos;
8700
Chris Lattner9f269e42005-08-08 19:11:57 +00008701 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008702 ++NumSunkInst;
8703 return true;
8704}
8705
Chris Lattner1443bc52006-05-11 17:11:52 +00008706/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008707/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008708/// if possible.
8709static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8710 if (!TD) return CE;
8711
8712 Constant *Ptr = CE->getOperand(0);
8713 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8714 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8715 // If this is a constant expr gep that is effectively computing an
8716 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8717 bool isFoldableGEP = true;
8718 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8719 if (!isa<ConstantInt>(CE->getOperand(i)))
8720 isFoldableGEP = false;
8721 if (isFoldableGEP) {
8722 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8723 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008724 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00008725 C = ConstantExpr::getIntegerCast(C, TD->getIntPtrType(), true /*SExt*/);
8726 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00008727 }
8728 }
8729
8730 return CE;
8731}
8732
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008733
8734/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8735/// all reachable code to the worklist.
8736///
8737/// This has a couple of tricks to make the code faster and more powerful. In
8738/// particular, we constant fold and DCE instructions as we go, to avoid adding
8739/// them to the worklist (this significantly speeds up instcombine on code where
8740/// many instructions are dead or constant). Additionally, if we find a branch
8741/// whose condition is a known constant, we only visit the reachable successors.
8742///
8743static void AddReachableCodeToWorklist(BasicBlock *BB,
8744 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008745 std::vector<Instruction*> &WorkList,
8746 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008747 // We have now visited this block! If we've already been here, bail out.
8748 if (!Visited.insert(BB).second) return;
8749
8750 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8751 Instruction *Inst = BBI++;
8752
8753 // DCE instruction if trivially dead.
8754 if (isInstructionTriviallyDead(Inst)) {
8755 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008756 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008757 Inst->eraseFromParent();
8758 continue;
8759 }
8760
8761 // ConstantProp instruction if trivially constant.
8762 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008763 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8764 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008765 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008766 Inst->replaceAllUsesWith(C);
8767 ++NumConstProp;
8768 Inst->eraseFromParent();
8769 continue;
8770 }
8771
8772 WorkList.push_back(Inst);
8773 }
8774
8775 // Recursively visit successors. If this is a branch or switch on a constant,
8776 // only visit the reachable successor.
8777 TerminatorInst *TI = BB->getTerminator();
8778 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8779 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8780 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008781 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8782 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008783 return;
8784 }
8785 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8786 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8787 // See if this is an explicit destination.
8788 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8789 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008790 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008791 return;
8792 }
8793
8794 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008795 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008796 return;
8797 }
8798 }
8799
8800 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008801 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008802}
8803
Chris Lattner113f4f42002-06-25 16:13:24 +00008804bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008805 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008806 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008807
Chris Lattner4ed40f72005-07-07 20:40:38 +00008808 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008809 // Do a depth-first traversal of the function, populate the worklist with
8810 // the reachable instructions. Ignore blocks that are not reachable. Keep
8811 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008812 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008813 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008814
Chris Lattner4ed40f72005-07-07 20:40:38 +00008815 // Do a quick scan over the function. If we find any blocks that are
8816 // unreachable, remove any instructions inside of them. This prevents
8817 // the instcombine code from having to deal with some bad special cases.
8818 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8819 if (!Visited.count(BB)) {
8820 Instruction *Term = BB->getTerminator();
8821 while (Term != BB->begin()) { // Remove instrs bottom-up
8822 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008823
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008824 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00008825 ++NumDeadInst;
8826
8827 if (!I->use_empty())
8828 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8829 I->eraseFromParent();
8830 }
8831 }
8832 }
Chris Lattnerca081252001-12-14 16:52:21 +00008833
8834 while (!WorkList.empty()) {
8835 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8836 WorkList.pop_back();
8837
Chris Lattner1443bc52006-05-11 17:11:52 +00008838 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008839 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008840 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008841 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008842 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008843 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008844
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008845 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008846
8847 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008848 removeFromWorkList(I);
8849 continue;
8850 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008851
Chris Lattner1443bc52006-05-11 17:11:52 +00008852 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008853 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008854 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8855 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008856 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008857
Chris Lattner1443bc52006-05-11 17:11:52 +00008858 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008859 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008860 ReplaceInstUsesWith(*I, C);
8861
Chris Lattner99f48c62002-09-02 04:59:56 +00008862 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008863 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008864 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008865 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008866 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008867
Chris Lattner39c98bb2004-12-08 23:43:58 +00008868 // See if we can trivially sink this instruction to a successor basic block.
8869 if (I->hasOneUse()) {
8870 BasicBlock *BB = I->getParent();
8871 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8872 if (UserParent != BB) {
8873 bool UserIsSuccessor = false;
8874 // See if the user is one of our successors.
8875 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8876 if (*SI == UserParent) {
8877 UserIsSuccessor = true;
8878 break;
8879 }
8880
8881 // If the user is one of our immediate successors, and if that successor
8882 // only has us as a predecessors (we'd have to split the critical edge
8883 // otherwise), we can keep going.
8884 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8885 next(pred_begin(UserParent)) == pred_end(UserParent))
8886 // Okay, the CFG is simple enough, try to sink this instruction.
8887 Changed |= TryToSinkInstruction(I, UserParent);
8888 }
8889 }
8890
Chris Lattnerca081252001-12-14 16:52:21 +00008891 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008892 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008893 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008894 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008895 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008896 DOUT << "IC: Old = " << *I
8897 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008898
Chris Lattner396dbfe2004-06-09 05:08:07 +00008899 // Everything uses the new instruction now.
8900 I->replaceAllUsesWith(Result);
8901
8902 // Push the new instruction and any users onto the worklist.
8903 WorkList.push_back(Result);
8904 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008905
8906 // Move the name to the new instruction first...
8907 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008908 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008909
8910 // Insert the new instruction into the basic block...
8911 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008912 BasicBlock::iterator InsertPos = I;
8913
8914 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8915 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8916 ++InsertPos;
8917
8918 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008919
Chris Lattner63d75af2004-05-01 23:27:23 +00008920 // Make sure that we reprocess all operands now that we reduced their
8921 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008922 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8923 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8924 WorkList.push_back(OpI);
8925
Chris Lattner396dbfe2004-06-09 05:08:07 +00008926 // Instructions can end up on the worklist more than once. Make sure
8927 // we do not process an instruction that has been deleted.
8928 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008929
8930 // Erase the old instruction.
8931 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008932 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008933 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008934
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008935 // If the instruction was modified, it's possible that it is now dead.
8936 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008937 if (isInstructionTriviallyDead(I)) {
8938 // Make sure we process all operands now that we are reducing their
8939 // use counts.
8940 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8941 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8942 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008943
Chris Lattner63d75af2004-05-01 23:27:23 +00008944 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008945 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008946 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008947 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008948 } else {
8949 WorkList.push_back(Result);
8950 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008951 }
Chris Lattner053c0932002-05-14 15:24:07 +00008952 }
Chris Lattner260ab202002-04-18 17:39:14 +00008953 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008954 }
8955 }
8956
Chris Lattner260ab202002-04-18 17:39:14 +00008957 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008958}
8959
Brian Gaeke38b79e82004-07-27 17:43:21 +00008960FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008961 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008962}
Brian Gaeke960707c2003-11-11 22:41:34 +00008963