blob: 448637abf65db3661865e0aac3ce0d9dda941a9b [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 Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000091
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
95 ///
96 /// Return the specified operand before it is turned into an undef.
97 ///
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
100
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
106 }
107
108 return R;
109 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000110
Chris Lattner99f48c62002-09-02 04:59:56 +0000111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000113 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000114 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000115
Chris Lattnerf12cc842002-04-28 21:27:06 +0000116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000117 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000118 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000120 }
121
Chris Lattner69193f92004-04-05 01:30:19 +0000122 TargetData &getTargetData() const { return *TD; }
123
Chris Lattner260ab202002-04-18 17:39:14 +0000124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
126 // Return Value:
127 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000128 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000129 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000130 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000134 Instruction *visitURem(BinaryOperator &I);
135 Instruction *visitSRem(BinaryOperator &I);
136 Instruction *visitFRem(BinaryOperator &I);
137 Instruction *commonRemTransforms(BinaryOperator &I);
138 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000139 Instruction *commonDivTransforms(BinaryOperator &I);
140 Instruction *commonIDivTransforms(BinaryOperator &I);
141 Instruction *visitUDiv(BinaryOperator &I);
142 Instruction *visitSDiv(BinaryOperator &I);
143 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 Instruction *visitAnd(BinaryOperator &I);
145 Instruction *visitOr (BinaryOperator &I);
146 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000147 Instruction *visitSetCondInst(SetCondInst &I);
148 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149
Chris Lattner0798af32005-01-13 20:14:25 +0000150 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
151 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000155 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000156 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
157 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000158 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000159 Instruction *visitCallInst(CallInst &CI);
160 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000161 Instruction *visitPHINode(PHINode &PN);
162 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000163 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000164 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000165 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000166 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000167 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000168 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000169 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000170 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000171 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000172
173 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000175
Chris Lattner970c33a2003-06-19 17:00:31 +0000176 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000177 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000178 bool transformConstExprCastCall(CallSite CS);
179
Chris Lattner69193f92004-04-05 01:30:19 +0000180 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000181 // InsertNewInstBefore - insert an instruction New before instruction Old
182 // in the program. Add the new instruction to the worklist.
183 //
Chris Lattner623826c2004-09-28 21:48:02 +0000184 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000185 assert(New && New->getParent() == 0 &&
186 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 BasicBlock *BB = Old.getParent();
188 BB->getInstList().insert(&Old, New); // Insert inst
189 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000190 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000191 }
192
Chris Lattner7e794272004-09-24 15:21:34 +0000193 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
194 /// This also adds the cast to the worklist. Finally, this returns the
195 /// cast.
196 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
197 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000198
Chris Lattnere79d2492006-04-06 19:19:17 +0000199 if (Constant *CV = dyn_cast<Constant>(V))
200 return ConstantExpr::getCast(CV, Ty);
201
Chris Lattner7e794272004-09-24 15:21:34 +0000202 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
203 WorkList.push_back(C);
204 return C;
205 }
206
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000207 // ReplaceInstUsesWith - This method is to be used when an instruction is
208 // found to be dead, replacable with another preexisting expression. Here
209 // we add all uses of I to the worklist, replace all uses of I with the new
210 // value, then return I, so that the inst combiner will know that I was
211 // modified.
212 //
213 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000214 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000215 if (&I != V) {
216 I.replaceAllUsesWith(V);
217 return &I;
218 } else {
219 // If we are replacing the instruction with itself, this must be in a
220 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000221 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000222 return &I;
223 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000225
Chris Lattner2590e512006-02-07 06:56:34 +0000226 // UpdateValueUsesWith - This method is to be used when an value is
227 // found to be replacable with another preexisting expression or was
228 // updated. Here we add all uses of I to the worklist, replace all uses of
229 // I with the new value (unless the instruction was just updated), then
230 // return true, so that the inst combiner will know that I was modified.
231 //
232 bool UpdateValueUsesWith(Value *Old, Value *New) {
233 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
234 if (Old != New)
235 Old->replaceAllUsesWith(New);
236 if (Instruction *I = dyn_cast<Instruction>(Old))
237 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000238 if (Instruction *I = dyn_cast<Instruction>(New))
239 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000240 return true;
241 }
242
Chris Lattner51ea1272004-02-28 05:22:00 +0000243 // EraseInstFromFunction - When dealing with an instruction that has side
244 // effects or produces a void value, we can't rely on DCE to delete the
245 // instruction. Instead, visit methods should return the value returned by
246 // this function.
247 Instruction *EraseInstFromFunction(Instruction &I) {
248 assert(I.use_empty() && "Cannot erase instruction that is used!");
249 AddUsesToWorkList(I);
250 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000251 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000252 return 0; // Don't do anything with FI
253 }
254
Chris Lattner3ac7c262003-08-13 20:16:26 +0000255 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000256 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
257 /// InsertBefore instruction. This is specialized a bit to avoid inserting
258 /// casts that are known to not do anything...
259 ///
260 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
261 Instruction *InsertBefore);
262
Chris Lattner7fb29e12003-03-11 00:12:48 +0000263 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000264 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000266
Chris Lattner0157e7f2006-02-11 09:31:47 +0000267 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
268 uint64_t &KnownZero, uint64_t &KnownOne,
269 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000270
Chris Lattner2deeaea2006-10-05 06:55:50 +0000271 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
272 uint64_t &UndefElts, unsigned Depth = 0);
273
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000274 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
275 // PHI node as operand #0, see if we can fold the instruction into the PHI
276 // (which is only possible if all operands to the PHI are constants).
277 Instruction *FoldOpIntoPhi(Instruction &I);
278
Chris Lattner7515cab2004-11-14 19:13:23 +0000279 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
280 // operator and they all are only used by the PHI, PHI together their
281 // inputs, and do the operation once, to the result of the PHI.
282 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000283 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
284
285
Chris Lattnerba1cb382003-09-19 17:17:26 +0000286 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
287 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000288
289 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
290 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000291 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
292 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000293 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000294 Instruction *MatchBSwap(BinaryOperator &I);
295
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000296 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000297 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000298
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000299 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000300}
301
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000303// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000304static unsigned getComplexity(Value *V) {
305 if (isa<Instruction>(V)) {
306 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000307 return 3;
308 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000310 if (isa<Argument>(V)) return 3;
311 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000312}
Chris Lattner260ab202002-04-18 17:39:14 +0000313
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314// isOnlyUse - Return true if this instruction will be deleted if we stop using
315// it.
316static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000317 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000318}
319
Chris Lattnere79e8542004-02-23 06:38:22 +0000320// getPromotedType - Return the specified type promoted as it would be to pass
321// though a va_arg area...
322static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000323 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000324 case Type::SByteTyID:
325 case Type::ShortTyID: return Type::IntTy;
326 case Type::UByteTyID:
327 case Type::UShortTyID: return Type::UIntTy;
328 case Type::FloatTyID: return Type::DoubleTy;
329 default: return Ty;
330 }
331}
332
Chris Lattner567b81f2005-09-13 00:40:14 +0000333/// isCast - If the specified operand is a CastInst or a constant expr cast,
334/// return the operand value, otherwise return null.
335static Value *isCast(Value *V) {
336 if (CastInst *I = dyn_cast<CastInst>(V))
337 return I->getOperand(0);
338 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
339 if (CE->getOpcode() == Instruction::Cast)
340 return CE->getOperand(0);
341 return 0;
342}
343
Chris Lattner1d441ad2006-05-06 09:00:16 +0000344enum CastType {
345 Noop = 0,
346 Truncate = 1,
347 Signext = 2,
348 Zeroext = 3
349};
350
351/// getCastType - In the future, we will split the cast instruction into these
352/// various types. Until then, we have to do the analysis here.
353static CastType getCastType(const Type *Src, const Type *Dest) {
354 assert(Src->isIntegral() && Dest->isIntegral() &&
355 "Only works on integral types!");
356 unsigned SrcSize = Src->getPrimitiveSizeInBits();
357 unsigned DestSize = Dest->getPrimitiveSizeInBits();
358
359 if (SrcSize == DestSize) return Noop;
360 if (SrcSize > DestSize) return Truncate;
361 if (Src->isSigned()) return Signext;
362 return Zeroext;
363}
364
365
366// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
367// instruction.
368//
369static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
370 const Type *DstTy, TargetData *TD) {
371
372 // It is legal to eliminate the instruction if casting A->B->A if the sizes
373 // are identical and the bits don't get reinterpreted (for example
374 // int->float->int would not be allowed).
375 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
376 return true;
377
378 // If we are casting between pointer and integer types, treat pointers as
379 // integers of the appropriate size for the code below.
380 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
381 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
382 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
383
384 // Allow free casting and conversion of sizes as long as the sign doesn't
385 // change...
386 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
387 CastType FirstCast = getCastType(SrcTy, MidTy);
388 CastType SecondCast = getCastType(MidTy, DstTy);
389
390 // Capture the effect of these two casts. If the result is a legal cast,
391 // the CastType is stored here, otherwise a special code is used.
392 static const unsigned CastResult[] = {
393 // First cast is noop
394 0, 1, 2, 3,
395 // First cast is a truncate
396 1, 1, 4, 4, // trunc->extend is not safe to eliminate
397 // First cast is a sign ext
398 2, 5, 2, 4, // signext->zeroext never ok
399 // First cast is a zero ext
400 3, 5, 3, 3,
401 };
402
403 unsigned Result = CastResult[FirstCast*4+SecondCast];
404 switch (Result) {
405 default: assert(0 && "Illegal table value!");
406 case 0:
407 case 1:
408 case 2:
409 case 3:
410 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
411 // truncates, we could eliminate more casts.
412 return (unsigned)getCastType(SrcTy, DstTy) == Result;
413 case 4:
414 return false; // Not possible to eliminate this here.
415 case 5:
416 // Sign or zero extend followed by truncate is always ok if the result
417 // is a truncate or noop.
418 CastType ResultCast = getCastType(SrcTy, DstTy);
419 if (ResultCast == Noop || ResultCast == Truncate)
420 return true;
421 // Otherwise we are still growing the value, we are only safe if the
422 // result will match the sign/zeroextendness of the result.
423 return ResultCast == FirstCast;
424 }
425 }
426
427 // If this is a cast from 'float -> double -> integer', cast from
428 // 'float -> integer' directly, as the value isn't changed by the
429 // float->double conversion.
430 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
431 DstTy->isIntegral() &&
432 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
433 return true;
434
435 // Packed type conversions don't modify bits.
436 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
437 return true;
438
439 return false;
440}
441
442/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443/// in any code being generated. It does not require codegen if V is simple
444/// enough or if the cast can be folded into other casts.
445static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
448 // If this is a noop cast, it isn't real codegen.
449 if (V->getType()->isLosslesslyConvertibleTo(Ty))
450 return false;
451
Chris Lattner99155be2006-05-25 23:24:33 +0000452 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000453 if (const CastInst *CI = dyn_cast<CastInst>(V))
454 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
455 TD))
456 return false;
457 return true;
458}
459
460/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
461/// InsertBefore instruction. This is specialized a bit to avoid inserting
462/// casts that are known to not do anything...
463///
464Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
465 Instruction *InsertBefore) {
466 if (V->getType() == DestTy) return V;
467 if (Constant *C = dyn_cast<Constant>(V))
468 return ConstantExpr::getCast(C, DestTy);
469
Reid Spencer00c482b2006-10-26 19:19:06 +0000470 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000471}
472
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000473// SimplifyCommutative - This performs a few simplifications for commutative
474// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000475//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000476// 1. Order operands such that they are listed from right (least complex) to
477// left (most complex). This puts constants before unary operators before
478// binary operators.
479//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000480// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
481// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000484 bool Changed = false;
485 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
486 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000487
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000488 if (!I.isAssociative()) return Changed;
489 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
491 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
492 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000493 Constant *Folded = ConstantExpr::get(I.getOpcode(),
494 cast<Constant>(I.getOperand(1)),
495 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496 I.setOperand(0, Op->getOperand(0));
497 I.setOperand(1, Folded);
498 return true;
499 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
500 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
501 isOnlyUse(Op) && isOnlyUse(Op1)) {
502 Constant *C1 = cast<Constant>(Op->getOperand(1));
503 Constant *C2 = cast<Constant>(Op1->getOperand(1));
504
505 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000507 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
508 Op1->getOperand(0),
509 Op1->getName(), &I);
510 WorkList.push_back(New);
511 I.setOperand(0, New);
512 I.setOperand(1, Folded);
513 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000514 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000515 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000516 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000517}
Chris Lattnerca081252001-12-14 16:52:21 +0000518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
520// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000521//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522static inline Value *dyn_castNegVal(Value *V) {
523 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000524 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525
Chris Lattner9ad0d552004-12-14 20:08:06 +0000526 // Constants can be considered to be negated values if they can be folded.
527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
528 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000529 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000530}
531
Chris Lattnerbb74e222003-03-10 23:06:50 +0000532static inline Value *dyn_castNotVal(Value *V) {
533 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000534 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000535
536 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000537 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000538 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000539 return 0;
540}
541
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542// dyn_castFoldableMul - If this value is a multiply that can be folded into
543// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000544// non-constant operand of the multiply, and set CST to point to the multiplier.
545// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000548 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000550 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000551 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000552 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000553 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000554 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000555 // The multiplier is really 1 << CST.
556 Constant *One = ConstantInt::get(V->getType(), 1);
557 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
558 return I->getOperand(0);
559 }
560 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000561 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000562}
Chris Lattner31ae8632002-08-14 17:51:49 +0000563
Chris Lattner0798af32005-01-13 20:14:25 +0000564/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565/// expression, return it.
566static User *dyn_castGetElementPtr(Value *V) {
567 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569 if (CE->getOpcode() == Instruction::GetElementPtr)
570 return cast<User>(V);
571 return false;
572}
573
Chris Lattner623826c2004-09-28 21:48:02 +0000574// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000575static ConstantInt *AddOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getAdd(C,
577 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000578}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000579static ConstantInt *SubOne(ConstantInt *C) {
580 return cast<ConstantInt>(ConstantExpr::getSub(C,
581 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000582}
583
Chris Lattner0157e7f2006-02-11 09:31:47 +0000584/// GetConstantInType - Return a ConstantInt with the specified type and value.
585///
Chris Lattneree0f2802006-02-12 02:07:56 +0000586static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000587 if (Ty->isUnsigned())
588 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000589 else if (Ty->getTypeID() == Type::BoolTyID)
590 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000591 int64_t SVal = Val;
592 SVal <<= 64-Ty->getPrimitiveSizeInBits();
593 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000594 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000595}
596
597
Chris Lattner4534dd592006-02-09 07:38:58 +0000598/// ComputeMaskedBits - Determine which of the bits specified in Mask are
599/// known to be either zero or one and return them in the KnownZero/KnownOne
600/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
601/// processing.
602static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
603 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000604 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
605 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000606 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000607 // optimized based on the contradictory assumption that it is non-zero.
608 // Because instcombine aggressively folds operations with undef args anyway,
609 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000610 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
611 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000612 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000613 KnownZero = ~KnownOne & Mask;
614 return;
615 }
616
617 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000618 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000619 return; // Limit search depth.
620
621 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000622 Instruction *I = dyn_cast<Instruction>(V);
623 if (!I) return;
624
Chris Lattnerfb296922006-05-04 17:33:35 +0000625 Mask &= V->getType()->getIntegralTypeMask();
626
Chris Lattner0157e7f2006-02-11 09:31:47 +0000627 switch (I->getOpcode()) {
628 case Instruction::And:
629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
631 Mask &= ~KnownZero;
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
640 return;
641 case Instruction::Or:
642 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
643 Mask &= ~KnownOne;
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
647
648 // Output known-0 bits are only known if clear in both the LHS & RHS.
649 KnownZero &= KnownZero2;
650 // Output known-1 are known to be set if set in either the LHS | RHS.
651 KnownOne |= KnownOne2;
652 return;
653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
664 return;
665 }
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
675 return;
676 case Instruction::Cast: {
677 const Type *SrcTy = I->getOperand(0)->getType();
678 if (!SrcTy->isIntegral()) return;
679
680 // If this is an integer truncate or noop, just look in the input.
681 if (SrcTy->getPrimitiveSizeInBits() >=
682 I->getType()->getPrimitiveSizeInBits()) {
683 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000684 return;
685 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000686
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 // Sign or Zero extension. Compute the bits in the result that are not
688 // present in the input.
689 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
690 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000691
Chris Lattner0157e7f2006-02-11 09:31:47 +0000692 // Handle zero extension.
693 if (!SrcTy->isSigned()) {
694 Mask &= SrcTy->getIntegralTypeMask();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // The top bits are known to be zero.
698 KnownZero |= NewBits;
699 } else {
700 // Sign extension.
701 Mask &= SrcTy->getIntegralTypeMask();
702 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
703 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000704
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // If the sign bit of the input is known set or clear, then we know the
706 // top bits of the result.
707 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
708 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000709 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000710 KnownOne &= ~NewBits;
711 } else if (KnownOne & InSignBit) { // Input sign bit known set
712 KnownOne |= NewBits;
713 KnownZero &= ~NewBits;
714 } else { // Input sign bit unknown
715 KnownZero &= ~NewBits;
716 KnownOne &= ~NewBits;
717 }
718 }
719 return;
720 }
721 case Instruction::Shl:
722 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000723 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
724 uint64_t ShiftAmt = SA->getZExtValue();
725 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000726 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
727 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000728 KnownZero <<= ShiftAmt;
729 KnownOne <<= ShiftAmt;
730 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000731 return;
732 }
733 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000734 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000735 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000736 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000737 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000738 uint64_t ShiftAmt = SA->getZExtValue();
739 uint64_t HighBits = (1ULL << ShiftAmt)-1;
740 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000741
Reid Spencerfdff9382006-11-08 06:47:33 +0000742 // Unsigned shift right.
743 Mask <<= ShiftAmt;
744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
746 KnownZero >>= ShiftAmt;
747 KnownOne >>= ShiftAmt;
748 KnownZero |= HighBits; // high bits known zero.
749 return;
750 }
751 break;
752 case Instruction::AShr:
753 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
754 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
755 // Compute the new bits that are at the top now.
756 uint64_t ShiftAmt = SA->getZExtValue();
757 uint64_t HighBits = (1ULL << ShiftAmt)-1;
758 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
759
760 // Signed shift right.
761 Mask <<= ShiftAmt;
762 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
763 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
764 KnownZero >>= ShiftAmt;
765 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000766
Reid Spencerfdff9382006-11-08 06:47:33 +0000767 // Handle the sign bits.
768 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
769 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000770
Reid Spencerfdff9382006-11-08 06:47:33 +0000771 if (KnownZero & SignBit) { // New bits are known zero.
772 KnownZero |= HighBits;
773 } else if (KnownOne & SignBit) { // New bits are known one.
774 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000775 }
776 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000777 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000778 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000779 }
Chris Lattner92a68652006-02-07 08:05:22 +0000780}
781
782/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
783/// this predicate to simplify operations downstream. Mask is known to be zero
784/// for bits that V cannot have.
785static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000786 uint64_t KnownZero, KnownOne;
787 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
788 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
789 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000790}
791
Chris Lattner0157e7f2006-02-11 09:31:47 +0000792/// ShrinkDemandedConstant - Check to see if the specified operand of the
793/// specified instruction is a constant integer. If so, check to see if there
794/// are any bits set in the constant that are not demanded. If so, shrink the
795/// constant and return true.
796static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
797 uint64_t Demanded) {
798 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
799 if (!OpC) return false;
800
801 // If there are no bits set that aren't demanded, nothing to do.
802 if ((~Demanded & OpC->getZExtValue()) == 0)
803 return false;
804
805 // This is producing any bits that are not needed, shrink the RHS.
806 uint64_t Val = Demanded & OpC->getZExtValue();
807 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
808 return true;
809}
810
Chris Lattneree0f2802006-02-12 02:07:56 +0000811// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
812// set of known zero and one bits, compute the maximum and minimum values that
813// could have the specified known zero and known one bits, returning them in
814// min/max.
815static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
816 uint64_t KnownZero,
817 uint64_t KnownOne,
818 int64_t &Min, int64_t &Max) {
819 uint64_t TypeBits = Ty->getIntegralTypeMask();
820 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821
822 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
823
824 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
825 // bit if it is unknown.
826 Min = KnownOne;
827 Max = KnownOne|UnknownBits;
828
829 if (SignBit & UnknownBits) { // Sign bit is unknown
830 Min |= SignBit;
831 Max &= ~SignBit;
832 }
833
834 // Sign extend the min/max values.
835 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
836 Min = (Min << ShAmt) >> ShAmt;
837 Max = (Max << ShAmt) >> ShAmt;
838}
839
840// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
841// a set of known zero and one bits, compute the maximum and minimum values that
842// could have the specified known zero and known one bits, returning them in
843// min/max.
844static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
845 uint64_t KnownZero,
846 uint64_t KnownOne,
847 uint64_t &Min,
848 uint64_t &Max) {
849 uint64_t TypeBits = Ty->getIntegralTypeMask();
850 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
851
852 // The minimum value is when the unknown bits are all zeros.
853 Min = KnownOne;
854 // The maximum value is when the unknown bits are all ones.
855 Max = KnownOne|UnknownBits;
856}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857
858
859/// SimplifyDemandedBits - Look at V. At this point, we know that only the
860/// DemandedMask bits of the result of V are ever used downstream. If we can
861/// use this information to simplify V, do so and return true. Otherwise,
862/// analyze the expression and return a mask of KnownOne and KnownZero bits for
863/// the expression (used to simplify the caller). The KnownZero/One bits may
864/// only be accurate for those bits in the DemandedMask.
865bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
866 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000867 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
869 // We know all of the bits for a constant!
870 KnownOne = CI->getZExtValue() & DemandedMask;
871 KnownZero = ~KnownOne & DemandedMask;
872 return false;
873 }
874
875 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000876 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000877 if (Depth != 0) { // Not at the root.
878 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
879 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000880 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 }
Chris Lattner2590e512006-02-07 06:56:34 +0000882 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883 // just set the DemandedMask to all bits.
884 DemandedMask = V->getType()->getIntegralTypeMask();
885 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000886 if (V != UndefValue::get(V->getType()))
887 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
888 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000889 } else if (Depth == 6) { // Limit search depth.
890 return false;
891 }
892
893 Instruction *I = dyn_cast<Instruction>(V);
894 if (!I) return false; // Only analyze instructions.
895
Chris Lattnerfb296922006-05-04 17:33:35 +0000896 DemandedMask &= V->getType()->getIntegralTypeMask();
897
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000899 switch (I->getOpcode()) {
900 default: break;
901 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 // If either the LHS or the RHS are Zero, the result is zero.
903 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
904 KnownZero, KnownOne, Depth+1))
905 return true;
906 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
907
908 // If something is known zero on the RHS, the bits aren't demanded on the
909 // LHS.
910 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
911 KnownZero2, KnownOne2, Depth+1))
912 return true;
913 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
914
915 // If all of the demanded bits are known one on one side, return the other.
916 // These bits cannot contribute to the result of the 'and'.
917 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
918 return UpdateValueUsesWith(I, I->getOperand(0));
919 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
920 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000921
922 // If all of the demanded bits in the inputs are known zeros, return zero.
923 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
924 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
925
Chris Lattner0157e7f2006-02-11 09:31:47 +0000926 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000927 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000928 return UpdateValueUsesWith(I, I);
929
930 // Output known-1 bits are only known if set in both the LHS & RHS.
931 KnownOne &= KnownOne2;
932 // Output known-0 are known to be clear if zero in either the LHS | RHS.
933 KnownZero |= KnownZero2;
934 break;
935 case Instruction::Or:
936 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
937 KnownZero, KnownOne, Depth+1))
938 return true;
939 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
940 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
941 KnownZero2, KnownOne2, Depth+1))
942 return true;
943 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
944
945 // If all of the demanded bits are known zero on one side, return the other.
946 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000947 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000948 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000949 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000950 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000951
952 // If all of the potentially set bits on one side are known to be set on
953 // the other side, just use the 'other' side.
954 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
955 (DemandedMask & (~KnownZero)))
956 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000957 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
958 (DemandedMask & (~KnownZero2)))
959 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000960
961 // If the RHS is a constant, see if we can simplify it.
962 if (ShrinkDemandedConstant(I, 1, DemandedMask))
963 return UpdateValueUsesWith(I, I);
964
965 // Output known-0 bits are only known if clear in both the LHS & RHS.
966 KnownZero &= KnownZero2;
967 // Output known-1 are known to be set if set in either the LHS | RHS.
968 KnownOne |= KnownOne2;
969 break;
970 case Instruction::Xor: {
971 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
972 KnownZero, KnownOne, Depth+1))
973 return true;
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
975 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
976 KnownZero2, KnownOne2, Depth+1))
977 return true;
978 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
979
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'xor'.
982 if ((DemandedMask & KnownZero) == DemandedMask)
983 return UpdateValueUsesWith(I, I->getOperand(0));
984 if ((DemandedMask & KnownZero2) == DemandedMask)
985 return UpdateValueUsesWith(I, I->getOperand(1));
986
987 // Output known-0 bits are known if clear or set in both the LHS & RHS.
988 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
989 // Output known-1 are known to be set if set in only one of the LHS, RHS.
990 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
991
992 // If all of the unknown bits are known to be zero on one side or the other
993 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000994 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000995 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
996 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
997 Instruction *Or =
998 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
999 I->getName());
1000 InsertNewInstBefore(Or, *I);
1001 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001002 }
1003 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004
Chris Lattner5b2edb12006-02-12 08:02:11 +00001005 // If all of the demanded bits on one side are known, and all of the set
1006 // bits on that side are also known to be set on the other side, turn this
1007 // into an AND, as we know the bits will be cleared.
1008 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1009 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1010 if ((KnownOne & KnownOne2) == KnownOne) {
1011 Constant *AndC = GetConstantInType(I->getType(),
1012 ~KnownOne & DemandedMask);
1013 Instruction *And =
1014 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1015 InsertNewInstBefore(And, *I);
1016 return UpdateValueUsesWith(I, And);
1017 }
1018 }
1019
Chris Lattner0157e7f2006-02-11 09:31:47 +00001020 // If the RHS is a constant, see if we can simplify it.
1021 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024
1025 KnownZero = KnownZeroOut;
1026 KnownOne = KnownOneOut;
1027 break;
1028 }
1029 case Instruction::Select:
1030 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1031 KnownZero, KnownOne, Depth+1))
1032 return true;
1033 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1034 KnownZero2, KnownOne2, Depth+1))
1035 return true;
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1038
1039 // If the operands are constants, see if we can simplify them.
1040 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1041 return UpdateValueUsesWith(I, I);
1042 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return UpdateValueUsesWith(I, I);
1044
1045 // Only known if known in both the LHS and RHS.
1046 KnownOne &= KnownOne2;
1047 KnownZero &= KnownZero2;
1048 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001049 case Instruction::Cast: {
1050 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001052
Chris Lattner0157e7f2006-02-11 09:31:47 +00001053 // If this is an integer truncate or noop, just look in the input.
1054 if (SrcTy->getPrimitiveSizeInBits() >=
1055 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001056 // Cast to bool is a comparison against 0, which demands all bits. We
1057 // can't propagate anything useful up.
1058 if (I->getType() == Type::BoolTy)
1059 break;
1060
Chris Lattner0157e7f2006-02-11 09:31:47 +00001061 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1062 KnownZero, KnownOne, Depth+1))
1063 return true;
1064 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1065 break;
1066 }
1067
1068 // Sign or Zero extension. Compute the bits in the result that are not
1069 // present in the input.
1070 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1071 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1072
1073 // Handle zero extension.
1074 if (!SrcTy->isSigned()) {
1075 DemandedMask &= SrcTy->getIntegralTypeMask();
1076 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1077 KnownZero, KnownOne, Depth+1))
1078 return true;
1079 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1080 // The top bits are known to be zero.
1081 KnownZero |= NewBits;
1082 } else {
1083 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001084 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1085 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1086
1087 // If any of the sign extended bits are demanded, we know that the sign
1088 // bit is demanded.
1089 if (NewBits & DemandedMask)
1090 InputDemandedBits |= InSignBit;
1091
1092 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001093 KnownZero, KnownOne, Depth+1))
1094 return true;
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1096
1097 // If the sign bit of the input is known set or clear, then we know the
1098 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001099
Chris Lattner0157e7f2006-02-11 09:31:47 +00001100 // If the input sign bit is known zero, or if the NewBits are not demanded
1101 // convert this into a zero extension.
1102 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001103 // Convert to unsigned first.
Reid Spencer00c482b2006-10-26 19:19:06 +00001104 Value *NewVal =
1105 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001106 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001108 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001109 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001110 } else if (KnownOne & InSignBit) { // Input sign bit known set
1111 KnownOne |= NewBits;
1112 KnownZero &= ~NewBits;
1113 } else { // Input sign bit unknown
1114 KnownZero &= ~NewBits;
1115 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001116 }
Chris Lattner2590e512006-02-07 06:56:34 +00001117 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001118 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001119 }
Chris Lattner2590e512006-02-07 06:56:34 +00001120 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001121 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1122 uint64_t ShiftAmt = SA->getZExtValue();
1123 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001124 KnownZero, KnownOne, Depth+1))
1125 return true;
1126 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001127 KnownZero <<= ShiftAmt;
1128 KnownOne <<= ShiftAmt;
1129 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001130 }
Chris Lattner2590e512006-02-07 06:56:34 +00001131 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001132 case Instruction::LShr:
1133 // For a logical shift right
1134 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1135 unsigned ShiftAmt = SA->getZExtValue();
1136
1137 // Compute the new bits that are at the top now.
1138 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1139 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1140 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1141 // Unsigned shift right.
1142 if (SimplifyDemandedBits(I->getOperand(0),
1143 (DemandedMask << ShiftAmt) & TypeMask,
1144 KnownZero, KnownOne, Depth+1))
1145 return true;
1146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1147 KnownZero &= TypeMask;
1148 KnownOne &= TypeMask;
1149 KnownZero >>= ShiftAmt;
1150 KnownOne >>= ShiftAmt;
1151 KnownZero |= HighBits; // high bits known zero.
1152 }
1153 break;
1154 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001155 // If this is an arithmetic shift right and only the low-bit is set, we can
1156 // always convert this into a logical shr, even if the shift amount is
1157 // variable. The low bit of the shift cannot be an input sign bit unless
1158 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001159 if (DemandedMask == 1) {
1160 // Perform the logical shift right.
1161 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1162 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001163 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001164 return UpdateValueUsesWith(I, NewVal);
1165 }
1166
Reid Spencere0fc4df2006-10-20 07:07:24 +00001167 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001169
1170 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001171 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1172 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001173 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001174 // Signed shift right.
1175 if (SimplifyDemandedBits(I->getOperand(0),
1176 (DemandedMask << ShiftAmt) & TypeMask,
1177 KnownZero, KnownOne, Depth+1))
1178 return true;
1179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1180 KnownZero &= TypeMask;
1181 KnownOne &= TypeMask;
1182 KnownZero >>= ShiftAmt;
1183 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001184
Reid Spencerfdff9382006-11-08 06:47:33 +00001185 // Handle the sign bits.
1186 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1187 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001188
Reid Spencerfdff9382006-11-08 06:47:33 +00001189 // If the input sign bit is known to be zero, or if none of the top bits
1190 // are demanded, turn this into an unsigned shift right.
1191 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1192 // Perform the logical shift right.
1193 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1194 SA, I->getName());
1195 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1196 return UpdateValueUsesWith(I, NewVal);
1197 } else if (KnownOne & SignBit) { // New bits are known one.
1198 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001199 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001200 }
Chris Lattner2590e512006-02-07 06:56:34 +00001201 break;
1202 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001203
1204 // If the client is only demanding bits that we know, return the known
1205 // constant.
1206 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1207 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001208 return false;
1209}
1210
Chris Lattner2deeaea2006-10-05 06:55:50 +00001211
1212/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1213/// 64 or fewer elements. DemandedElts contains the set of elements that are
1214/// actually used by the caller. This method analyzes which elements of the
1215/// operand are undef and returns that information in UndefElts.
1216///
1217/// If the information about demanded elements can be used to simplify the
1218/// operation, the operation is simplified, then the resultant value is
1219/// returned. This returns null if no change was made.
1220Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1221 uint64_t &UndefElts,
1222 unsigned Depth) {
1223 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1224 assert(VWidth <= 64 && "Vector too wide to analyze!");
1225 uint64_t EltMask = ~0ULL >> (64-VWidth);
1226 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1227 "Invalid DemandedElts!");
1228
1229 if (isa<UndefValue>(V)) {
1230 // If the entire vector is undefined, just return this info.
1231 UndefElts = EltMask;
1232 return 0;
1233 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1234 UndefElts = EltMask;
1235 return UndefValue::get(V->getType());
1236 }
1237
1238 UndefElts = 0;
1239 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1240 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1241 Constant *Undef = UndefValue::get(EltTy);
1242
1243 std::vector<Constant*> Elts;
1244 for (unsigned i = 0; i != VWidth; ++i)
1245 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1246 Elts.push_back(Undef);
1247 UndefElts |= (1ULL << i);
1248 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1249 Elts.push_back(Undef);
1250 UndefElts |= (1ULL << i);
1251 } else { // Otherwise, defined.
1252 Elts.push_back(CP->getOperand(i));
1253 }
1254
1255 // If we changed the constant, return it.
1256 Constant *NewCP = ConstantPacked::get(Elts);
1257 return NewCP != CP ? NewCP : 0;
1258 } else if (isa<ConstantAggregateZero>(V)) {
1259 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1260 // set to undef.
1261 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1262 Constant *Zero = Constant::getNullValue(EltTy);
1263 Constant *Undef = UndefValue::get(EltTy);
1264 std::vector<Constant*> Elts;
1265 for (unsigned i = 0; i != VWidth; ++i)
1266 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1267 UndefElts = DemandedElts ^ EltMask;
1268 return ConstantPacked::get(Elts);
1269 }
1270
1271 if (!V->hasOneUse()) { // Other users may use these bits.
1272 if (Depth != 0) { // Not at the root.
1273 // TODO: Just compute the UndefElts information recursively.
1274 return false;
1275 }
1276 return false;
1277 } else if (Depth == 10) { // Limit search depth.
1278 return false;
1279 }
1280
1281 Instruction *I = dyn_cast<Instruction>(V);
1282 if (!I) return false; // Only analyze instructions.
1283
1284 bool MadeChange = false;
1285 uint64_t UndefElts2;
1286 Value *TmpV;
1287 switch (I->getOpcode()) {
1288 default: break;
1289
1290 case Instruction::InsertElement: {
1291 // If this is a variable index, we don't know which element it overwrites.
1292 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001293 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001294 if (Idx == 0) {
1295 // Note that we can't propagate undef elt info, because we don't know
1296 // which elt is getting updated.
1297 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1298 UndefElts2, Depth+1);
1299 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1300 break;
1301 }
1302
1303 // If this is inserting an element that isn't demanded, remove this
1304 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001305 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001306 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1307 return AddSoonDeadInstToWorklist(*I, 0);
1308
1309 // Otherwise, the element inserted overwrites whatever was there, so the
1310 // input demanded set is simpler than the output set.
1311 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1312 DemandedElts & ~(1ULL << IdxNo),
1313 UndefElts, Depth+1);
1314 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1315
1316 // The inserted element is defined.
1317 UndefElts |= 1ULL << IdxNo;
1318 break;
1319 }
1320
1321 case Instruction::And:
1322 case Instruction::Or:
1323 case Instruction::Xor:
1324 case Instruction::Add:
1325 case Instruction::Sub:
1326 case Instruction::Mul:
1327 // div/rem demand all inputs, because they don't want divide by zero.
1328 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1329 UndefElts, Depth+1);
1330 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1331 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1332 UndefElts2, Depth+1);
1333 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1334
1335 // Output elements are undefined if both are undefined. Consider things
1336 // like undef&0. The result is known zero, not undef.
1337 UndefElts &= UndefElts2;
1338 break;
1339
1340 case Instruction::Call: {
1341 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1342 if (!II) break;
1343 switch (II->getIntrinsicID()) {
1344 default: break;
1345
1346 // Binary vector operations that work column-wise. A dest element is a
1347 // function of the corresponding input elements from the two inputs.
1348 case Intrinsic::x86_sse_sub_ss:
1349 case Intrinsic::x86_sse_mul_ss:
1350 case Intrinsic::x86_sse_min_ss:
1351 case Intrinsic::x86_sse_max_ss:
1352 case Intrinsic::x86_sse2_sub_sd:
1353 case Intrinsic::x86_sse2_mul_sd:
1354 case Intrinsic::x86_sse2_min_sd:
1355 case Intrinsic::x86_sse2_max_sd:
1356 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1357 UndefElts, Depth+1);
1358 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1359 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1360 UndefElts2, Depth+1);
1361 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1362
1363 // If only the low elt is demanded and this is a scalarizable intrinsic,
1364 // scalarize it now.
1365 if (DemandedElts == 1) {
1366 switch (II->getIntrinsicID()) {
1367 default: break;
1368 case Intrinsic::x86_sse_sub_ss:
1369 case Intrinsic::x86_sse_mul_ss:
1370 case Intrinsic::x86_sse2_sub_sd:
1371 case Intrinsic::x86_sse2_mul_sd:
1372 // TODO: Lower MIN/MAX/ABS/etc
1373 Value *LHS = II->getOperand(1);
1374 Value *RHS = II->getOperand(2);
1375 // Extract the element as scalars.
1376 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1377 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1378
1379 switch (II->getIntrinsicID()) {
1380 default: assert(0 && "Case stmts out of sync!");
1381 case Intrinsic::x86_sse_sub_ss:
1382 case Intrinsic::x86_sse2_sub_sd:
1383 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1384 II->getName()), *II);
1385 break;
1386 case Intrinsic::x86_sse_mul_ss:
1387 case Intrinsic::x86_sse2_mul_sd:
1388 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1389 II->getName()), *II);
1390 break;
1391 }
1392
1393 Instruction *New =
1394 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1395 II->getName());
1396 InsertNewInstBefore(New, *II);
1397 AddSoonDeadInstToWorklist(*II, 0);
1398 return New;
1399 }
1400 }
1401
1402 // Output elements are undefined if both are undefined. Consider things
1403 // like undef&0. The result is known zero, not undef.
1404 UndefElts &= UndefElts2;
1405 break;
1406 }
1407 break;
1408 }
1409 }
1410 return MadeChange ? I : 0;
1411}
1412
Chris Lattner623826c2004-09-28 21:48:02 +00001413// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1414// true when both operands are equal...
1415//
1416static bool isTrueWhenEqual(Instruction &I) {
1417 return I.getOpcode() == Instruction::SetEQ ||
1418 I.getOpcode() == Instruction::SetGE ||
1419 I.getOpcode() == Instruction::SetLE;
1420}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001421
1422/// AssociativeOpt - Perform an optimization on an associative operator. This
1423/// function is designed to check a chain of associative operators for a
1424/// potential to apply a certain optimization. Since the optimization may be
1425/// applicable if the expression was reassociated, this checks the chain, then
1426/// reassociates the expression as necessary to expose the optimization
1427/// opportunity. This makes use of a special Functor, which must define
1428/// 'shouldApply' and 'apply' methods.
1429///
1430template<typename Functor>
1431Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1432 unsigned Opcode = Root.getOpcode();
1433 Value *LHS = Root.getOperand(0);
1434
1435 // Quick check, see if the immediate LHS matches...
1436 if (F.shouldApply(LHS))
1437 return F.apply(Root);
1438
1439 // Otherwise, if the LHS is not of the same opcode as the root, return.
1440 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001441 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001442 // Should we apply this transform to the RHS?
1443 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1444
1445 // If not to the RHS, check to see if we should apply to the LHS...
1446 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1447 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1448 ShouldApply = true;
1449 }
1450
1451 // If the functor wants to apply the optimization to the RHS of LHSI,
1452 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1453 if (ShouldApply) {
1454 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001455
Chris Lattnerb8b97502003-08-13 19:01:45 +00001456 // Now all of the instructions are in the current basic block, go ahead
1457 // and perform the reassociation.
1458 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1459
1460 // First move the selected RHS to the LHS of the root...
1461 Root.setOperand(0, LHSI->getOperand(1));
1462
1463 // Make what used to be the LHS of the root be the user of the root...
1464 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001465 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001466 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1467 return 0;
1468 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001469 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001470 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001471 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1472 BasicBlock::iterator ARI = &Root; ++ARI;
1473 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1474 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001475
1476 // Now propagate the ExtraOperand down the chain of instructions until we
1477 // get to LHSI.
1478 while (TmpLHSI != LHSI) {
1479 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001480 // Move the instruction to immediately before the chain we are
1481 // constructing to avoid breaking dominance properties.
1482 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1483 BB->getInstList().insert(ARI, NextLHSI);
1484 ARI = NextLHSI;
1485
Chris Lattnerb8b97502003-08-13 19:01:45 +00001486 Value *NextOp = NextLHSI->getOperand(1);
1487 NextLHSI->setOperand(1, ExtraOperand);
1488 TmpLHSI = NextLHSI;
1489 ExtraOperand = NextOp;
1490 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001491
Chris Lattnerb8b97502003-08-13 19:01:45 +00001492 // Now that the instructions are reassociated, have the functor perform
1493 // the transformation...
1494 return F.apply(Root);
1495 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001496
Chris Lattnerb8b97502003-08-13 19:01:45 +00001497 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1498 }
1499 return 0;
1500}
1501
1502
1503// AddRHS - Implements: X + X --> X << 1
1504struct AddRHS {
1505 Value *RHS;
1506 AddRHS(Value *rhs) : RHS(rhs) {}
1507 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1508 Instruction *apply(BinaryOperator &Add) const {
1509 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1510 ConstantInt::get(Type::UByteTy, 1));
1511 }
1512};
1513
1514// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1515// iff C1&C2 == 0
1516struct AddMaskingAnd {
1517 Constant *C2;
1518 AddMaskingAnd(Constant *c) : C2(c) {}
1519 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001520 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001521 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001522 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001523 }
1524 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001525 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001526 }
1527};
1528
Chris Lattner86102b82005-01-01 16:22:27 +00001529static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001530 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001531 if (isa<CastInst>(I)) {
1532 if (Constant *SOC = dyn_cast<Constant>(SO))
1533 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534
Chris Lattner86102b82005-01-01 16:22:27 +00001535 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1536 SO->getName() + ".cast"), I);
1537 }
1538
Chris Lattner183b3362004-04-09 19:05:30 +00001539 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001540 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1541 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001542
Chris Lattner183b3362004-04-09 19:05:30 +00001543 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1544 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001545 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1546 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001547 }
1548
1549 Value *Op0 = SO, *Op1 = ConstOperand;
1550 if (!ConstIsRHS)
1551 std::swap(Op0, Op1);
1552 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1554 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1555 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1556 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001557 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001558 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001559 abort();
1560 }
Chris Lattner86102b82005-01-01 16:22:27 +00001561 return IC->InsertNewInstBefore(New, I);
1562}
1563
1564// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1565// constant as the other operand, try to fold the binary operator into the
1566// select arguments. This also works for Cast instructions, which obviously do
1567// not have a second operand.
1568static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1569 InstCombiner *IC) {
1570 // Don't modify shared select instructions
1571 if (!SI->hasOneUse()) return 0;
1572 Value *TV = SI->getOperand(1);
1573 Value *FV = SI->getOperand(2);
1574
1575 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001576 // Bool selects with constant operands can be folded to logical ops.
1577 if (SI->getType() == Type::BoolTy) return 0;
1578
Chris Lattner86102b82005-01-01 16:22:27 +00001579 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1580 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1581
1582 return new SelectInst(SI->getCondition(), SelectTrueVal,
1583 SelectFalseVal);
1584 }
1585 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001586}
1587
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001588
1589/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1590/// node as operand #0, see if we can fold the instruction into the PHI (which
1591/// is only possible if all operands to the PHI are constants).
1592Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1593 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001594 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001595 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001596
Chris Lattner04689872006-09-09 22:02:56 +00001597 // Check to see if all of the operands of the PHI are constants. If there is
1598 // one non-constant value, remember the BB it is. If there is more than one
1599 // bail out.
1600 BasicBlock *NonConstBB = 0;
1601 for (unsigned i = 0; i != NumPHIValues; ++i)
1602 if (!isa<Constant>(PN->getIncomingValue(i))) {
1603 if (NonConstBB) return 0; // More than one non-const value.
1604 NonConstBB = PN->getIncomingBlock(i);
1605
1606 // If the incoming non-constant value is in I's block, we have an infinite
1607 // loop.
1608 if (NonConstBB == I.getParent())
1609 return 0;
1610 }
1611
1612 // If there is exactly one non-constant value, we can insert a copy of the
1613 // operation in that block. However, if this is a critical edge, we would be
1614 // inserting the computation one some other paths (e.g. inside a loop). Only
1615 // do this if the pred block is unconditionally branching into the phi block.
1616 if (NonConstBB) {
1617 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1618 if (!BI || !BI->isUnconditional()) return 0;
1619 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001620
1621 // Okay, we can do the transformation: create the new PHI node.
1622 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1623 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001624 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001625 InsertNewInstBefore(NewPN, *PN);
1626
1627 // Next, add all of the operands to the PHI.
1628 if (I.getNumOperands() == 2) {
1629 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001630 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001631 Value *InV;
1632 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1633 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1634 } else {
1635 assert(PN->getIncomingBlock(i) == NonConstBB);
1636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1637 InV = BinaryOperator::create(BO->getOpcode(),
1638 PN->getIncomingValue(i), C, "phitmp",
1639 NonConstBB->getTerminator());
1640 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1641 InV = new ShiftInst(SI->getOpcode(),
1642 PN->getIncomingValue(i), C, "phitmp",
1643 NonConstBB->getTerminator());
1644 else
1645 assert(0 && "Unknown binop!");
1646
1647 WorkList.push_back(cast<Instruction>(InV));
1648 }
1649 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001650 }
1651 } else {
1652 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1653 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001654 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001655 Value *InV;
1656 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1657 InV = ConstantExpr::getCast(InC, RetTy);
1658 } else {
1659 assert(PN->getIncomingBlock(i) == NonConstBB);
1660 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1661 NonConstBB->getTerminator());
1662 WorkList.push_back(cast<Instruction>(InV));
1663 }
1664 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001665 }
1666 }
1667 return ReplaceInstUsesWith(I, NewPN);
1668}
1669
Chris Lattner113f4f42002-06-25 16:13:24 +00001670Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001671 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001672 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001673
Chris Lattnercf4a9962004-04-10 22:01:55 +00001674 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001675 // X + undef -> undef
1676 if (isa<UndefValue>(RHS))
1677 return ReplaceInstUsesWith(I, RHS);
1678
Chris Lattnercf4a9962004-04-10 22:01:55 +00001679 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001680 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1681 if (RHSC->isNullValue())
1682 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001683 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1684 if (CFP->isExactlyValue(-0.0))
1685 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001686 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001687
Chris Lattnercf4a9962004-04-10 22:01:55 +00001688 // X + (signbit) --> X ^ signbit
1689 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001690 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001691 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001692 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001693 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001694
1695 if (isa<PHINode>(LHS))
1696 if (Instruction *NV = FoldOpIntoPhi(I))
1697 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001698
Chris Lattner330628a2006-01-06 17:59:59 +00001699 ConstantInt *XorRHS = 0;
1700 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001701 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1702 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1703 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1704 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1705
1706 uint64_t C0080Val = 1ULL << 31;
1707 int64_t CFF80Val = -C0080Val;
1708 unsigned Size = 32;
1709 do {
1710 if (TySizeBits > Size) {
1711 bool Found = false;
1712 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1713 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1714 if (RHSSExt == CFF80Val) {
1715 if (XorRHS->getZExtValue() == C0080Val)
1716 Found = true;
1717 } else if (RHSZExt == C0080Val) {
1718 if (XorRHS->getSExtValue() == CFF80Val)
1719 Found = true;
1720 }
1721 if (Found) {
1722 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001723 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001724 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001725 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001726 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001727 Size = 0; // Not a sign ext, but can't be any others either.
1728 goto FoundSExt;
1729 }
1730 }
1731 Size >>= 1;
1732 C0080Val >>= Size;
1733 CFF80Val >>= Size;
1734 } while (Size >= 8);
1735
1736FoundSExt:
1737 const Type *MiddleType = 0;
1738 switch (Size) {
1739 default: break;
1740 case 32: MiddleType = Type::IntTy; break;
1741 case 16: MiddleType = Type::ShortTy; break;
1742 case 8: MiddleType = Type::SByteTy; break;
1743 }
1744 if (MiddleType) {
1745 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1746 InsertNewInstBefore(NewTrunc, I);
1747 return new CastInst(NewTrunc, I.getType());
1748 }
1749 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001750 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001751
Chris Lattnerb8b97502003-08-13 19:01:45 +00001752 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001753 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001754 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001755
1756 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1757 if (RHSI->getOpcode() == Instruction::Sub)
1758 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1759 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1760 }
1761 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1762 if (LHSI->getOpcode() == Instruction::Sub)
1763 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1764 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1765 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001766 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001767
Chris Lattner147e9752002-05-08 22:46:53 +00001768 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001769 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001770 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001771
1772 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001773 if (!isa<Constant>(RHS))
1774 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001775 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001776
Misha Brukmanb1c93172005-04-21 23:48:37 +00001777
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001778 ConstantInt *C2;
1779 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1780 if (X == RHS) // X*C + X --> X * (C+1)
1781 return BinaryOperator::createMul(RHS, AddOne(C2));
1782
1783 // X*C1 + X*C2 --> X * (C1+C2)
1784 ConstantInt *C1;
1785 if (X == dyn_castFoldableMul(RHS, C1))
1786 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001787 }
1788
1789 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001790 if (dyn_castFoldableMul(RHS, C2) == LHS)
1791 return BinaryOperator::createMul(LHS, AddOne(C2));
1792
Chris Lattner57c8d992003-02-18 19:57:07 +00001793
Chris Lattnerb8b97502003-08-13 19:01:45 +00001794 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001795 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001796 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001797
Chris Lattnerb9cde762003-10-02 15:11:26 +00001798 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001799 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001800 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1801 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1802 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001803 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001804
Chris Lattnerbff91d92004-10-08 05:07:56 +00001805 // (X & FF00) + xx00 -> (X+xx00) & FF00
1806 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1807 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1808 if (Anded == CRHS) {
1809 // See if all bits from the first bit set in the Add RHS up are included
1810 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001811 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001812
1813 // Form a mask of all bits from the lowest bit added through the top.
1814 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001815 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001816
1817 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001818 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001819
Chris Lattnerbff91d92004-10-08 05:07:56 +00001820 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1821 // Okay, the xform is safe. Insert the new add pronto.
1822 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1823 LHS->getName()), I);
1824 return BinaryOperator::createAnd(NewAdd, C2);
1825 }
1826 }
1827 }
1828
Chris Lattnerd4252a72004-07-30 07:50:03 +00001829 // Try to fold constant add into select arguments.
1830 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001831 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001832 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001833 }
1834
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001835 // add (cast *A to intptrtype) B ->
1836 // cast (GEP (cast *A to sbyte*) B) ->
1837 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001838 {
1839 CastInst* CI = dyn_cast<CastInst>(LHS);
1840 Value* Other = RHS;
1841 if (!CI) {
1842 CI = dyn_cast<CastInst>(RHS);
1843 Other = LHS;
1844 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001845 if (CI && CI->getType()->isSized() &&
1846 (CI->getType()->getPrimitiveSize() ==
1847 TD->getIntPtrType()->getPrimitiveSize())
1848 && isa<PointerType>(CI->getOperand(0)->getType())) {
1849 Value* I2 = InsertCastBefore(CI->getOperand(0),
1850 PointerType::get(Type::SByteTy), I);
1851 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1852 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001853 }
1854 }
1855
Chris Lattner113f4f42002-06-25 16:13:24 +00001856 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001857}
1858
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001859// isSignBit - Return true if the value represented by the constant only has the
1860// highest order bit set.
1861static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001862 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001863 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001864}
1865
Chris Lattner022167f2004-03-13 00:11:49 +00001866/// RemoveNoopCast - Strip off nonconverting casts from the value.
1867///
1868static Value *RemoveNoopCast(Value *V) {
1869 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1870 const Type *CTy = CI->getType();
1871 const Type *OpTy = CI->getOperand(0)->getType();
1872 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001873 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001874 return RemoveNoopCast(CI->getOperand(0));
1875 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1876 return RemoveNoopCast(CI->getOperand(0));
1877 }
1878 return V;
1879}
1880
Chris Lattner113f4f42002-06-25 16:13:24 +00001881Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001882 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001883
Chris Lattnere6794492002-08-12 21:17:25 +00001884 if (Op0 == Op1) // sub X, X -> 0
1885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001886
Chris Lattnere6794492002-08-12 21:17:25 +00001887 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001888 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001889 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001890
Chris Lattner81a7a232004-10-16 18:11:37 +00001891 if (isa<UndefValue>(Op0))
1892 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1893 if (isa<UndefValue>(Op1))
1894 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1895
Chris Lattner8f2f5982003-11-05 01:06:05 +00001896 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1897 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001898 if (C->isAllOnesValue())
1899 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001900
Chris Lattner8f2f5982003-11-05 01:06:05 +00001901 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001902 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001903 if (match(Op1, m_Not(m_Value(X))))
1904 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001905 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001906 // -((uint)X >> 31) -> ((int)X >> 31)
1907 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001908 if (C->isNullValue()) {
1909 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1910 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001911 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001912 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001913 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001914 if (CU->getZExtValue() ==
1915 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001916 // Ok, the transformation is safe. Insert AShr.
1917 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1918 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001919 }
1920 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001921 }
1922 else if (SI->getOpcode() == Instruction::AShr) {
1923 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1924 // Check to see if we are shifting out everything but the sign bit.
1925 if (CU->getZExtValue() ==
1926 SI->getType()->getPrimitiveSizeInBits()-1) {
1927 // Ok, the transformation is safe. Insert LShr.
1928 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1929 CU, SI->getName());
1930 }
1931 }
1932 }
Chris Lattner022167f2004-03-13 00:11:49 +00001933 }
Chris Lattner183b3362004-04-09 19:05:30 +00001934
1935 // Try to fold constant sub into select arguments.
1936 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001937 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001938 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001939
1940 if (isa<PHINode>(Op0))
1941 if (Instruction *NV = FoldOpIntoPhi(I))
1942 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001943 }
1944
Chris Lattnera9be4492005-04-07 16:15:25 +00001945 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1946 if (Op1I->getOpcode() == Instruction::Add &&
1947 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001948 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001949 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001950 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001951 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001952 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1953 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1954 // C1-(X+C2) --> (C1-C2)-X
1955 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1956 Op1I->getOperand(0));
1957 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001958 }
1959
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001960 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001961 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1962 // is not used by anyone else...
1963 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001964 if (Op1I->getOpcode() == Instruction::Sub &&
1965 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001966 // Swap the two operands of the subexpr...
1967 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1968 Op1I->setOperand(0, IIOp1);
1969 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001970
Chris Lattner3082c5a2003-02-18 19:28:33 +00001971 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001972 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001973 }
1974
1975 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1976 //
1977 if (Op1I->getOpcode() == Instruction::And &&
1978 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1979 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1980
Chris Lattner396dbfe2004-06-09 05:08:07 +00001981 Value *NewNot =
1982 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001983 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001984 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001985
Reid Spencer3c514952006-10-16 23:08:08 +00001986 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001987 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001988 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001989 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001990 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001991 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001992 ConstantExpr::getNeg(DivRHS));
1993
Chris Lattner57c8d992003-02-18 19:57:07 +00001994 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001995 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001996 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001997 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001998 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001999 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002000 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002001 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002002 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002003
Chris Lattner47060462005-04-07 17:14:51 +00002004 if (!Op0->getType()->isFloatingPoint())
2005 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2006 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002007 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2008 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2009 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2010 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002011 } else if (Op0I->getOpcode() == Instruction::Sub) {
2012 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2013 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002014 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002015
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002016 ConstantInt *C1;
2017 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2018 if (X == Op1) { // X*C - X --> X * (C-1)
2019 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2020 return BinaryOperator::createMul(Op1, CP1);
2021 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002022
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002023 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2024 if (X == dyn_castFoldableMul(Op1, C2))
2025 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2026 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002027 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002028}
2029
Chris Lattnere79e8542004-02-23 06:38:22 +00002030/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2031/// really just returns true if the most significant (sign) bit is set.
2032static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2033 if (RHS->getType()->isSigned()) {
2034 // True if source is LHS < 0 or LHS <= -1
2035 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2036 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2037 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002038 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002039 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2040 // the size of the integer type.
2041 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002042 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002043 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002044 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002045 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002046 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002047 }
2048 return false;
2049}
2050
Chris Lattner113f4f42002-06-25 16:13:24 +00002051Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002052 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002053 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002054
Chris Lattner81a7a232004-10-16 18:11:37 +00002055 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2057
Chris Lattnere6794492002-08-12 21:17:25 +00002058 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002059 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2060 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002061
2062 // ((X << C1)*C2) == (X * (C2 << C1))
2063 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2064 if (SI->getOpcode() == Instruction::Shl)
2065 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002066 return BinaryOperator::createMul(SI->getOperand(0),
2067 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002068
Chris Lattnercce81be2003-09-11 22:24:54 +00002069 if (CI->isNullValue())
2070 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2071 if (CI->equalsInt(1)) // X * 1 == X
2072 return ReplaceInstUsesWith(I, Op0);
2073 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002074 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002075
Reid Spencere0fc4df2006-10-20 07:07:24 +00002076 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002077 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2078 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002079 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002080 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002081 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002082 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002083 if (Op1F->isNullValue())
2084 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002085
Chris Lattner3082c5a2003-02-18 19:28:33 +00002086 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2087 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2088 if (Op1F->getValue() == 1.0)
2089 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2090 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002091
2092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2093 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2094 isa<ConstantInt>(Op0I->getOperand(1))) {
2095 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2096 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2097 Op1, "tmp");
2098 InsertNewInstBefore(Add, I);
2099 Value *C1C2 = ConstantExpr::getMul(Op1,
2100 cast<Constant>(Op0I->getOperand(1)));
2101 return BinaryOperator::createAdd(Add, C1C2);
2102
2103 }
Chris Lattner183b3362004-04-09 19:05:30 +00002104
2105 // Try to fold constant mul into select arguments.
2106 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002107 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002108 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002109
2110 if (isa<PHINode>(Op0))
2111 if (Instruction *NV = FoldOpIntoPhi(I))
2112 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002113 }
2114
Chris Lattner934a64cf2003-03-10 23:23:04 +00002115 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2116 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002117 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002118
Chris Lattner2635b522004-02-23 05:39:21 +00002119 // If one of the operands of the multiply is a cast from a boolean value, then
2120 // we know the bool is either zero or one, so this is a 'masking' multiply.
2121 // See if we can simplify things based on how the boolean was originally
2122 // formed.
2123 CastInst *BoolCast = 0;
2124 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2125 if (CI->getOperand(0)->getType() == Type::BoolTy)
2126 BoolCast = CI;
2127 if (!BoolCast)
2128 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2129 if (CI->getOperand(0)->getType() == Type::BoolTy)
2130 BoolCast = CI;
2131 if (BoolCast) {
2132 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2133 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2134 const Type *SCOpTy = SCIOp0->getType();
2135
Chris Lattnere79e8542004-02-23 06:38:22 +00002136 // If the setcc is true iff the sign bit of X is set, then convert this
2137 // multiply into a shift/and combination.
2138 if (isa<ConstantInt>(SCIOp1) &&
2139 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002140 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002141 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002142 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002143 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002144 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002145 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002146 }
2147
2148 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002149 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002150 BoolCast->getOperand(0)->getName()+
2151 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002152
2153 // If the multiply type is not the same as the source type, sign extend
2154 // or truncate to the multiply type.
2155 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002156 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002157
Chris Lattner2635b522004-02-23 05:39:21 +00002158 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002159 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002160 }
2161 }
2162 }
2163
Chris Lattner113f4f42002-06-25 16:13:24 +00002164 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002165}
2166
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002167/// This function implements the transforms on div instructions that work
2168/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2169/// used by the visitors to those instructions.
2170/// @brief Transforms common to all three div instructions
2171Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002173
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002174 // undef / X -> 0
2175 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002177
2178 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002179 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002180 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002181
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002182 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002183 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2184 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002185 // same basic block, then we replace the select with Y, and the condition
2186 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002187 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002188 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002189 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2190 if (ST->isNullValue()) {
2191 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2192 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002193 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002194 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2195 I.setOperand(1, SI->getOperand(2));
2196 else
2197 UpdateValueUsesWith(SI, SI->getOperand(2));
2198 return &I;
2199 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002200
Chris Lattnerd79dc792006-09-09 20:26:32 +00002201 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2202 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2203 if (ST->isNullValue()) {
2204 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2205 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002206 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002207 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2208 I.setOperand(1, SI->getOperand(1));
2209 else
2210 UpdateValueUsesWith(SI, SI->getOperand(1));
2211 return &I;
2212 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002213 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002214
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002215 return 0;
2216}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002217
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002218/// This function implements the transforms common to both integer division
2219/// instructions (udiv and sdiv). It is called by the visitors to those integer
2220/// division instructions.
2221/// @brief Common integer divide transforms
2222Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2223 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2224
2225 if (Instruction *Common = commonDivTransforms(I))
2226 return Common;
2227
2228 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2229 // div X, 1 == X
2230 if (RHS->equalsInt(1))
2231 return ReplaceInstUsesWith(I, Op0);
2232
2233 // (X / C1) / C2 -> X / (C1*C2)
2234 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2235 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2236 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2237 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2238 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002239 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002240
2241 if (!RHS->isNullValue()) { // avoid X udiv 0
2242 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2243 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2244 return R;
2245 if (isa<PHINode>(Op0))
2246 if (Instruction *NV = FoldOpIntoPhi(I))
2247 return NV;
2248 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002249 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002250
Chris Lattner3082c5a2003-02-18 19:28:33 +00002251 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002252 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002253 if (LHS->equalsInt(0))
2254 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2255
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002256 return 0;
2257}
2258
2259Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2260 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2261
2262 // Handle the integer div common cases
2263 if (Instruction *Common = commonIDivTransforms(I))
2264 return Common;
2265
2266 // X udiv C^2 -> X >> C
2267 // Check to see if this is an unsigned division with an exact power of 2,
2268 // if so, convert to a right shift.
2269 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2270 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2271 if (isPowerOf2_64(Val)) {
2272 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002273 return new ShiftInst(Instruction::LShr, Op0,
2274 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002275 }
2276 }
2277
2278 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2279 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2280 if (RHSI->getOpcode() == Instruction::Shl &&
2281 isa<ConstantInt>(RHSI->getOperand(0))) {
2282 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2283 if (isPowerOf2_64(C1)) {
2284 Value *N = RHSI->getOperand(1);
2285 const Type* NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002286 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002287 Constant *C2V = ConstantInt::get(NTy, C2);
2288 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002289 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002290 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002291 }
2292 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002293 }
2294
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002295 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2296 // where C1&C2 are powers of two.
2297 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2298 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2299 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2300 if (!STO->isNullValue() && !STO->isNullValue()) {
2301 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2302 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2303 // Compute the shift amounts
2304 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002305 // Construct the "on true" case of the select
2306 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2307 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002308 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309 TSI = InsertNewInstBefore(TSI, I);
2310
2311 // Construct the "on false" case of the select
2312 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2313 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002314 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002315 FSI = InsertNewInstBefore(FSI, I);
2316
2317 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002318 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002319 }
2320 }
2321 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002322 return 0;
2323}
2324
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002325Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2326 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2327
2328 // Handle the integer div common cases
2329 if (Instruction *Common = commonIDivTransforms(I))
2330 return Common;
2331
2332 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2333 // sdiv X, -1 == -X
2334 if (RHS->isAllOnesValue())
2335 return BinaryOperator::createNeg(Op0);
2336
2337 // -X/C -> X/-C
2338 if (Value *LHSNeg = dyn_castNegVal(Op0))
2339 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2340 }
2341
2342 // If the sign bits of both operands are zero (i.e. we can prove they are
2343 // unsigned inputs), turn this into a udiv.
2344 if (I.getType()->isInteger()) {
2345 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2346 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2347 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2348 }
2349 }
2350
2351 return 0;
2352}
2353
2354Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2355 return commonDivTransforms(I);
2356}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002357
Chris Lattner85dda9a2006-03-02 06:50:58 +00002358/// GetFactor - If we can prove that the specified value is at least a multiple
2359/// of some factor, return that factor.
2360static Constant *GetFactor(Value *V) {
2361 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2362 return CI;
2363
2364 // Unless we can be tricky, we know this is a multiple of 1.
2365 Constant *Result = ConstantInt::get(V->getType(), 1);
2366
2367 Instruction *I = dyn_cast<Instruction>(V);
2368 if (!I) return Result;
2369
2370 if (I->getOpcode() == Instruction::Mul) {
2371 // Handle multiplies by a constant, etc.
2372 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2373 GetFactor(I->getOperand(1)));
2374 } else if (I->getOpcode() == Instruction::Shl) {
2375 // (X<<C) -> X * (1 << C)
2376 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2377 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2378 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2379 }
2380 } else if (I->getOpcode() == Instruction::And) {
2381 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2382 // X & 0xFFF0 is known to be a multiple of 16.
2383 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2384 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2385 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002386 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002387 }
2388 } else if (I->getOpcode() == Instruction::Cast) {
2389 Value *Op = I->getOperand(0);
2390 // Only handle int->int casts.
2391 if (!Op->getType()->isInteger()) return Result;
2392 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2393 }
2394 return Result;
2395}
2396
Reid Spencer7eb55b32006-11-02 01:53:59 +00002397/// This function implements the transforms on rem instructions that work
2398/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2399/// is used by the visitors to those instructions.
2400/// @brief Transforms common to all three rem instructions
2401Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002402 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002403
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002404 // 0 % X == 0, we don't need to preserve faults!
2405 if (Constant *LHS = dyn_cast<Constant>(Op0))
2406 if (LHS->isNullValue())
2407 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2408
2409 if (isa<UndefValue>(Op0)) // undef % X -> 0
2410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2411 if (isa<UndefValue>(Op1))
2412 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002413
2414 // Handle cases involving: rem X, (select Cond, Y, Z)
2415 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2416 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2417 // the same basic block, then we replace the select with Y, and the
2418 // condition of the select with false (if the cond value is in the same
2419 // BB). If the select has uses other than the div, this allows them to be
2420 // simplified also.
2421 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2422 if (ST->isNullValue()) {
2423 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2424 if (CondI && CondI->getParent() == I.getParent())
2425 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2426 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2427 I.setOperand(1, SI->getOperand(2));
2428 else
2429 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002430 return &I;
2431 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002432 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2433 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2434 if (ST->isNullValue()) {
2435 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2436 if (CondI && CondI->getParent() == I.getParent())
2437 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2438 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2439 I.setOperand(1, SI->getOperand(1));
2440 else
2441 UpdateValueUsesWith(SI, SI->getOperand(1));
2442 return &I;
2443 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002444 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002445
Reid Spencer7eb55b32006-11-02 01:53:59 +00002446 return 0;
2447}
2448
2449/// This function implements the transforms common to both integer remainder
2450/// instructions (urem and srem). It is called by the visitors to those integer
2451/// remainder instructions.
2452/// @brief Common integer remainder transforms
2453Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2454 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2455
2456 if (Instruction *common = commonRemTransforms(I))
2457 return common;
2458
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002459 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002460 // X % 0 == undef, we don't need to preserve faults!
2461 if (RHS->equalsInt(0))
2462 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2463
Chris Lattner3082c5a2003-02-18 19:28:33 +00002464 if (RHS->equalsInt(1)) // X % 1 == 0
2465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466
Chris Lattnerb70f1412006-02-28 05:49:21 +00002467 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2470 return R;
2471 } else if (isa<PHINode>(Op0I)) {
2472 if (Instruction *NV = FoldOpIntoPhi(I))
2473 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002474 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002475 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2476 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002477 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002478 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002479 }
2480
Reid Spencer7eb55b32006-11-02 01:53:59 +00002481 return 0;
2482}
2483
2484Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2485 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2486
2487 if (Instruction *common = commonIRemTransforms(I))
2488 return common;
2489
2490 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2491 // X urem C^2 -> X and C
2492 // Check to see if this is an unsigned remainder with an exact power of 2,
2493 // if so, convert to a bitwise and.
2494 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2495 if (isPowerOf2_64(C->getZExtValue()))
2496 return BinaryOperator::createAnd(Op0, SubOne(C));
2497 }
2498
Chris Lattner2e90b732006-02-05 07:54:04 +00002499 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002500 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2501 if (RHSI->getOpcode() == Instruction::Shl &&
2502 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002503 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002504 if (isPowerOf2_64(C1)) {
2505 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2506 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2507 "tmp"), I);
2508 return BinaryOperator::createAnd(Op0, Add);
2509 }
2510 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002511 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002512
Reid Spencer7eb55b32006-11-02 01:53:59 +00002513 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2514 // where C1&C2 are powers of two.
2515 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2516 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2517 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2518 // STO == 0 and SFO == 0 handled above.
2519 if (isPowerOf2_64(STO->getZExtValue()) &&
2520 isPowerOf2_64(SFO->getZExtValue())) {
2521 Value *TrueAnd = InsertNewInstBefore(
2522 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2523 Value *FalseAnd = InsertNewInstBefore(
2524 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2525 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2526 }
2527 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002528 }
2529
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002530 return 0;
2531}
2532
Reid Spencer7eb55b32006-11-02 01:53:59 +00002533Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2535
2536 if (Instruction *common = commonIRemTransforms(I))
2537 return common;
2538
2539 if (Value *RHSNeg = dyn_castNegVal(Op1))
2540 if (!isa<ConstantInt>(RHSNeg) ||
2541 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2542 // X % -Y -> X % Y
2543 AddUsesToWorkList(I);
2544 I.setOperand(1, RHSNeg);
2545 return &I;
2546 }
2547
2548 // If the top bits of both operands are zero (i.e. we can prove they are
2549 // unsigned inputs), turn this into a urem.
2550 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2551 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2552 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2553 return BinaryOperator::createURem(Op0, Op1, I.getName());
2554 }
2555
2556 return 0;
2557}
2558
2559Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002560 return commonRemTransforms(I);
2561}
2562
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002563// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002564static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002565 if (C->getType()->isUnsigned())
2566 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002567
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002568 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002569 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002570 int64_t Val = INT64_MAX; // All ones
2571 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002572 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002573}
2574
2575// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002576static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002577 if (C->getType()->isUnsigned())
2578 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002579
2580 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002581 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002582 int64_t Val = -1; // All ones
2583 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002584 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002585}
2586
Chris Lattner35167c32004-06-09 07:59:58 +00002587// isOneBitSet - Return true if there is exactly one bit set in the specified
2588// constant.
2589static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002590 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002591 return V && (V & (V-1)) == 0;
2592}
2593
Chris Lattner8fc5af42004-09-23 21:46:38 +00002594#if 0 // Currently unused
2595// isLowOnes - Return true if the constant is of the form 0+1+.
2596static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002597 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002598
2599 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002600 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002601
2602 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2603 return U && V && (U & V) == 0;
2604}
2605#endif
2606
2607// isHighOnes - Return true if the constant is of the form 1+0+.
2608// This is the same as lowones(~X).
2609static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002610 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002611 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002612
2613 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002614 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002615
2616 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2617 return U && V && (U & V) == 0;
2618}
2619
2620
Chris Lattner3ac7c262003-08-13 20:16:26 +00002621/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2622/// are carefully arranged to allow folding of expressions such as:
2623///
2624/// (A < B) | (A > B) --> (A != B)
2625///
2626/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2627/// represents that the comparison is true if A == B, and bit value '1' is true
2628/// if A < B.
2629///
2630static unsigned getSetCondCode(const SetCondInst *SCI) {
2631 switch (SCI->getOpcode()) {
2632 // False -> 0
2633 case Instruction::SetGT: return 1;
2634 case Instruction::SetEQ: return 2;
2635 case Instruction::SetGE: return 3;
2636 case Instruction::SetLT: return 4;
2637 case Instruction::SetNE: return 5;
2638 case Instruction::SetLE: return 6;
2639 // True -> 7
2640 default:
2641 assert(0 && "Invalid SetCC opcode!");
2642 return 0;
2643 }
2644}
2645
2646/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2647/// opcode and two operands into either a constant true or false, or a brand new
2648/// SetCC instruction.
2649static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2650 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002651 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002652 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2653 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2654 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2655 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2656 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2657 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002658 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002659 default: assert(0 && "Illegal SetCCCode!"); return 0;
2660 }
2661}
2662
2663// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2664struct FoldSetCCLogical {
2665 InstCombiner &IC;
2666 Value *LHS, *RHS;
2667 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2668 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2669 bool shouldApply(Value *V) const {
2670 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2671 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2672 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2673 return false;
2674 }
2675 Instruction *apply(BinaryOperator &Log) const {
2676 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2677 if (SCI->getOperand(0) != LHS) {
2678 assert(SCI->getOperand(1) == LHS);
2679 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2680 }
2681
2682 unsigned LHSCode = getSetCondCode(SCI);
2683 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2684 unsigned Code;
2685 switch (Log.getOpcode()) {
2686 case Instruction::And: Code = LHSCode & RHSCode; break;
2687 case Instruction::Or: Code = LHSCode | RHSCode; break;
2688 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002689 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002690 }
2691
2692 Value *RV = getSetCCValue(Code, LHS, RHS);
2693 if (Instruction *I = dyn_cast<Instruction>(RV))
2694 return I;
2695 // Otherwise, it's a constant boolean value...
2696 return IC.ReplaceInstUsesWith(Log, RV);
2697 }
2698};
2699
Chris Lattnerba1cb382003-09-19 17:17:26 +00002700// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2701// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2702// guaranteed to be either a shift instruction or a binary operator.
2703Instruction *InstCombiner::OptAndOp(Instruction *Op,
2704 ConstantIntegral *OpRHS,
2705 ConstantIntegral *AndRHS,
2706 BinaryOperator &TheAnd) {
2707 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002708 Constant *Together = 0;
2709 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002710 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002711
Chris Lattnerba1cb382003-09-19 17:17:26 +00002712 switch (Op->getOpcode()) {
2713 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002714 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002715 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2716 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002717 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002718 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002719 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002720 }
2721 break;
2722 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002723 if (Together == AndRHS) // (X | C) & C --> C
2724 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002725
Chris Lattner86102b82005-01-01 16:22:27 +00002726 if (Op->hasOneUse() && Together != OpRHS) {
2727 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2728 std::string Op0Name = Op->getName(); Op->setName("");
2729 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2730 InsertNewInstBefore(Or, TheAnd);
2731 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002732 }
2733 break;
2734 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002735 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002736 // Adding a one to a single bit bit-field should be turned into an XOR
2737 // of the bit. First thing to check is to see if this AND is with a
2738 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002739 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002740
2741 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002742 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002743
2744 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002745 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002746 // Ok, at this point, we know that we are masking the result of the
2747 // ADD down to exactly one bit. If the constant we are adding has
2748 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002749 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002750
Chris Lattnerba1cb382003-09-19 17:17:26 +00002751 // Check to see if any bits below the one bit set in AndRHSV are set.
2752 if ((AddRHS & (AndRHSV-1)) == 0) {
2753 // If not, the only thing that can effect the output of the AND is
2754 // the bit specified by AndRHSV. If that bit is set, the effect of
2755 // the XOR is to toggle the bit. If it is clear, then the ADD has
2756 // no effect.
2757 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2758 TheAnd.setOperand(0, X);
2759 return &TheAnd;
2760 } else {
2761 std::string Name = Op->getName(); Op->setName("");
2762 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002763 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002764 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002765 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002766 }
2767 }
2768 }
2769 }
2770 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002771
2772 case Instruction::Shl: {
2773 // We know that the AND will not produce any of the bits shifted in, so if
2774 // the anded constant includes them, clear them now!
2775 //
2776 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002777 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2778 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002779
Chris Lattner7e794272004-09-24 15:21:34 +00002780 if (CI == ShlMask) { // Masking out bits that the shift already masks
2781 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2782 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002783 TheAnd.setOperand(1, CI);
2784 return &TheAnd;
2785 }
2786 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002787 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002788 case Instruction::LShr:
2789 {
Chris Lattner2da29172003-09-19 19:05:02 +00002790 // We know that the AND will not produce any of the bits shifted in, so if
2791 // the anded constant includes them, clear them now! This only applies to
2792 // unsigned shifts, because a signed shr may bring in set bits!
2793 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002794 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2795 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2796 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002797
Reid Spencerfdff9382006-11-08 06:47:33 +00002798 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2799 return ReplaceInstUsesWith(TheAnd, Op);
2800 } else if (CI != AndRHS) {
2801 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2802 return &TheAnd;
2803 }
2804 break;
2805 }
2806 case Instruction::AShr:
2807 // Signed shr.
2808 // See if this is shifting in some sign extension, then masking it out
2809 // with an and.
2810 if (Op->hasOneUse()) {
2811 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2812 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2813 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2814 if (CI == AndRHS) { // Masking out bits shifted in.
2815 // Make the argument unsigned.
2816 Value *ShVal = Op->getOperand(0);
2817 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2818 OpRHS, Op->getName()),
2819 TheAnd);
2820 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2821 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002822 }
Chris Lattner2da29172003-09-19 19:05:02 +00002823 }
2824 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002825 }
2826 return 0;
2827}
2828
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002829
Chris Lattner6862fbd2004-09-29 17:40:11 +00002830/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2831/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2832/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2833/// insert new instructions.
2834Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2835 bool Inside, Instruction &IB) {
2836 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2837 "Lo is not <= Hi in range emission code!");
2838 if (Inside) {
2839 if (Lo == Hi) // Trivially false.
2840 return new SetCondInst(Instruction::SetNE, V, V);
2841 if (cast<ConstantIntegral>(Lo)->isMinValue())
2842 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002843
Chris Lattner6862fbd2004-09-29 17:40:11 +00002844 Constant *AddCST = ConstantExpr::getNeg(Lo);
2845 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2846 InsertNewInstBefore(Add, IB);
2847 // Convert to unsigned for the comparison.
2848 const Type *UnsType = Add->getType()->getUnsignedVersion();
2849 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2850 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2851 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2852 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2853 }
2854
2855 if (Lo == Hi) // Trivially true.
2856 return new SetCondInst(Instruction::SetEQ, V, V);
2857
2858 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002859
2860 // V < 0 || V >= Hi ->'V > Hi-1'
2861 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002862 return new SetCondInst(Instruction::SetGT, V, Hi);
2863
2864 // Emit X-Lo > Hi-Lo-1
2865 Constant *AddCST = ConstantExpr::getNeg(Lo);
2866 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2867 InsertNewInstBefore(Add, IB);
2868 // Convert to unsigned for the comparison.
2869 const Type *UnsType = Add->getType()->getUnsignedVersion();
2870 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2871 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2872 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2873 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2874}
2875
Chris Lattnerb4b25302005-09-18 07:22:02 +00002876// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2877// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2878// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2879// not, since all 1s are not contiguous.
2880static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002881 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002882 if (!isShiftedMask_64(V)) return false;
2883
2884 // look for the first zero bit after the run of ones
2885 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2886 // look for the first non-zero bit
2887 ME = 64-CountLeadingZeros_64(V);
2888 return true;
2889}
2890
2891
2892
2893/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2894/// where isSub determines whether the operator is a sub. If we can fold one of
2895/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002896///
2897/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2898/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2899/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2900///
2901/// return (A +/- B).
2902///
2903Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2904 ConstantIntegral *Mask, bool isSub,
2905 Instruction &I) {
2906 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2907 if (!LHSI || LHSI->getNumOperands() != 2 ||
2908 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2909
2910 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2911
2912 switch (LHSI->getOpcode()) {
2913 default: return 0;
2914 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002915 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2916 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002917 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002918 break;
2919
2920 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2921 // part, we don't need any explicit masks to take them out of A. If that
2922 // is all N is, ignore it.
2923 unsigned MB, ME;
2924 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002925 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2926 Mask >>= 64-MB+1;
2927 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002928 break;
2929 }
2930 }
Chris Lattneraf517572005-09-18 04:24:45 +00002931 return 0;
2932 case Instruction::Or:
2933 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002934 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002935 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002936 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002937 break;
2938 return 0;
2939 }
2940
2941 Instruction *New;
2942 if (isSub)
2943 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2944 else
2945 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2946 return InsertNewInstBefore(New, I);
2947}
2948
Chris Lattner113f4f42002-06-25 16:13:24 +00002949Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002950 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002951 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002952
Chris Lattner81a7a232004-10-16 18:11:37 +00002953 if (isa<UndefValue>(Op1)) // X & undef -> 0
2954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2955
Chris Lattner86102b82005-01-01 16:22:27 +00002956 // and X, X = X
2957 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002958 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002959
Chris Lattner5b2edb12006-02-12 08:02:11 +00002960 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002961 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002962 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002963 if (!isa<PackedType>(I.getType()) &&
2964 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002965 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002966 return &I;
2967
Chris Lattner86102b82005-01-01 16:22:27 +00002968 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002969 uint64_t AndRHSMask = AndRHS->getZExtValue();
2970 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002971 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002972
Chris Lattnerba1cb382003-09-19 17:17:26 +00002973 // Optimize a variety of ((val OP C1) & C2) combinations...
2974 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2975 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002976 Value *Op0LHS = Op0I->getOperand(0);
2977 Value *Op0RHS = Op0I->getOperand(1);
2978 switch (Op0I->getOpcode()) {
2979 case Instruction::Xor:
2980 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002981 // If the mask is only needed on one incoming arm, push it up.
2982 if (Op0I->hasOneUse()) {
2983 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2984 // Not masking anything out for the LHS, move to RHS.
2985 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2986 Op0RHS->getName()+".masked");
2987 InsertNewInstBefore(NewRHS, I);
2988 return BinaryOperator::create(
2989 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002990 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002991 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002992 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2993 // Not masking anything out for the RHS, move to LHS.
2994 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2995 Op0LHS->getName()+".masked");
2996 InsertNewInstBefore(NewLHS, I);
2997 return BinaryOperator::create(
2998 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2999 }
3000 }
3001
Chris Lattner86102b82005-01-01 16:22:27 +00003002 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003003 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003004 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3005 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3006 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3007 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3008 return BinaryOperator::createAnd(V, AndRHS);
3009 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3010 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003011 break;
3012
3013 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003014 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3015 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3016 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3017 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3018 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003019 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003020 }
3021
Chris Lattner16464b32003-07-23 19:25:52 +00003022 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003023 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003024 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003025 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3026 const Type *SrcTy = CI->getOperand(0)->getType();
3027
Chris Lattner2c14cf72005-08-07 07:03:10 +00003028 // If this is an integer truncation or change from signed-to-unsigned, and
3029 // if the source is an and/or with immediate, transform it. This
3030 // frequently occurs for bitfield accesses.
3031 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3032 if (SrcTy->getPrimitiveSizeInBits() >=
3033 I.getType()->getPrimitiveSizeInBits() &&
3034 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003035 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003036 if (CastOp->getOpcode() == Instruction::And) {
3037 // Change: and (cast (and X, C1) to T), C2
3038 // into : and (cast X to T), trunc(C1)&C2
3039 // This will folds the two ands together, which may allow other
3040 // simplifications.
3041 Instruction *NewCast =
3042 new CastInst(CastOp->getOperand(0), I.getType(),
3043 CastOp->getName()+".shrunk");
3044 NewCast = InsertNewInstBefore(NewCast, I);
3045
3046 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3047 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3048 return BinaryOperator::createAnd(NewCast, C3);
3049 } else if (CastOp->getOpcode() == Instruction::Or) {
3050 // Change: and (cast (or X, C1) to T), C2
3051 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3052 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3053 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3054 return ReplaceInstUsesWith(I, AndRHS);
3055 }
3056 }
Chris Lattner33217db2003-07-23 19:36:21 +00003057 }
Chris Lattner183b3362004-04-09 19:05:30 +00003058
3059 // Try to fold constant and into select arguments.
3060 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003061 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003062 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003063 if (isa<PHINode>(Op0))
3064 if (Instruction *NV = FoldOpIntoPhi(I))
3065 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003066 }
3067
Chris Lattnerbb74e222003-03-10 23:06:50 +00003068 Value *Op0NotVal = dyn_castNotVal(Op0);
3069 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003070
Chris Lattner023a4832004-06-18 06:07:51 +00003071 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3073
Misha Brukman9c003d82004-07-30 12:50:08 +00003074 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003075 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003076 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3077 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003078 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003079 return BinaryOperator::createNot(Or);
3080 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003081
3082 {
3083 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003084 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3085 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3086 return ReplaceInstUsesWith(I, Op1);
3087 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3088 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3089 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003090
3091 if (Op0->hasOneUse() &&
3092 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3093 if (A == Op1) { // (A^B)&A -> A&(A^B)
3094 I.swapOperands(); // Simplify below
3095 std::swap(Op0, Op1);
3096 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3097 cast<BinaryOperator>(Op0)->swapOperands();
3098 I.swapOperands(); // Simplify below
3099 std::swap(Op0, Op1);
3100 }
3101 }
3102 if (Op1->hasOneUse() &&
3103 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3104 if (B == Op0) { // B&(A^B) -> B&(B^A)
3105 cast<BinaryOperator>(Op1)->swapOperands();
3106 std::swap(A, B);
3107 }
3108 if (A == Op0) { // A&(A^B) -> A & ~B
3109 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3110 InsertNewInstBefore(NotB, I);
3111 return BinaryOperator::createAnd(A, NotB);
3112 }
3113 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003114 }
3115
Chris Lattner3082c5a2003-02-18 19:28:33 +00003116
Chris Lattner623826c2004-09-28 21:48:02 +00003117 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3118 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003119 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3120 return R;
3121
Chris Lattner623826c2004-09-28 21:48:02 +00003122 Value *LHSVal, *RHSVal;
3123 ConstantInt *LHSCst, *RHSCst;
3124 Instruction::BinaryOps LHSCC, RHSCC;
3125 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3126 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3127 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3128 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003129 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003130 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3131 // Ensure that the larger constant is on the RHS.
3132 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3133 SetCondInst *LHS = cast<SetCondInst>(Op0);
3134 if (cast<ConstantBool>(Cmp)->getValue()) {
3135 std::swap(LHS, RHS);
3136 std::swap(LHSCst, RHSCst);
3137 std::swap(LHSCC, RHSCC);
3138 }
3139
3140 // At this point, we know we have have two setcc instructions
3141 // comparing a value against two constants and and'ing the result
3142 // together. Because of the above check, we know that we only have
3143 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3144 // FoldSetCCLogical check above), that the two constants are not
3145 // equal.
3146 assert(LHSCst != RHSCst && "Compares not folded above?");
3147
3148 switch (LHSCC) {
3149 default: assert(0 && "Unknown integer condition code!");
3150 case Instruction::SetEQ:
3151 switch (RHSCC) {
3152 default: assert(0 && "Unknown integer condition code!");
3153 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3154 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003155 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003156 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3157 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3158 return ReplaceInstUsesWith(I, LHS);
3159 }
3160 case Instruction::SetNE:
3161 switch (RHSCC) {
3162 default: assert(0 && "Unknown integer condition code!");
3163 case Instruction::SetLT:
3164 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3165 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3166 break; // (X != 13 & X < 15) -> no change
3167 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3168 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3169 return ReplaceInstUsesWith(I, RHS);
3170 case Instruction::SetNE:
3171 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3172 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3173 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3174 LHSVal->getName()+".off");
3175 InsertNewInstBefore(Add, I);
3176 const Type *UnsType = Add->getType()->getUnsignedVersion();
3177 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3178 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3179 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3180 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3181 }
3182 break; // (X != 13 & X != 15) -> no change
3183 }
3184 break;
3185 case Instruction::SetLT:
3186 switch (RHSCC) {
3187 default: assert(0 && "Unknown integer condition code!");
3188 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3189 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003190 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003191 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3192 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3193 return ReplaceInstUsesWith(I, LHS);
3194 }
3195 case Instruction::SetGT:
3196 switch (RHSCC) {
3197 default: assert(0 && "Unknown integer condition code!");
3198 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3199 return ReplaceInstUsesWith(I, LHS);
3200 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3201 return ReplaceInstUsesWith(I, RHS);
3202 case Instruction::SetNE:
3203 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3204 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3205 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003206 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3207 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003208 }
3209 }
3210 }
3211 }
3212
Chris Lattner3af10532006-05-05 06:39:07 +00003213 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3214 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003215 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003216 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003217 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003218 // Only do this if the casts both really cause code to be generated.
3219 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3220 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003221 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3222 Op1C->getOperand(0),
3223 I.getName());
3224 InsertNewInstBefore(NewOp, I);
3225 return new CastInst(NewOp, I.getType());
3226 }
3227 }
3228
Chris Lattner113f4f42002-06-25 16:13:24 +00003229 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003230}
3231
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003232/// CollectBSwapParts - Look to see if the specified value defines a single byte
3233/// in the result. If it does, and if the specified byte hasn't been filled in
3234/// yet, fill it in and return false.
3235static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3236 Instruction *I = dyn_cast<Instruction>(V);
3237 if (I == 0) return true;
3238
3239 // If this is an or instruction, it is an inner node of the bswap.
3240 if (I->getOpcode() == Instruction::Or)
3241 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3242 CollectBSwapParts(I->getOperand(1), ByteValues);
3243
3244 // If this is a shift by a constant int, and it is "24", then its operand
3245 // defines a byte. We only handle unsigned types here.
3246 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3247 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003248 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003249 8*(ByteValues.size()-1))
3250 return true;
3251
3252 unsigned DestNo;
3253 if (I->getOpcode() == Instruction::Shl) {
3254 // X << 24 defines the top byte with the lowest of the input bytes.
3255 DestNo = ByteValues.size()-1;
3256 } else {
3257 // X >>u 24 defines the low byte with the highest of the input bytes.
3258 DestNo = 0;
3259 }
3260
3261 // If the destination byte value is already defined, the values are or'd
3262 // together, which isn't a bswap (unless it's an or of the same bits).
3263 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3264 return true;
3265 ByteValues[DestNo] = I->getOperand(0);
3266 return false;
3267 }
3268
3269 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3270 // don't have this.
3271 Value *Shift = 0, *ShiftLHS = 0;
3272 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3273 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3274 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3275 return true;
3276 Instruction *SI = cast<Instruction>(Shift);
3277
3278 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003279 if (ShiftAmt->getZExtValue() & 7 ||
3280 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003281 return true;
3282
3283 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3284 unsigned DestByte;
3285 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003286 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003287 break;
3288 // Unknown mask for bswap.
3289 if (DestByte == ByteValues.size()) return true;
3290
Reid Spencere0fc4df2006-10-20 07:07:24 +00003291 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003292 unsigned SrcByte;
3293 if (SI->getOpcode() == Instruction::Shl)
3294 SrcByte = DestByte - ShiftBytes;
3295 else
3296 SrcByte = DestByte + ShiftBytes;
3297
3298 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3299 if (SrcByte != ByteValues.size()-DestByte-1)
3300 return true;
3301
3302 // If the destination byte value is already defined, the values are or'd
3303 // together, which isn't a bswap (unless it's an or of the same bits).
3304 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3305 return true;
3306 ByteValues[DestByte] = SI->getOperand(0);
3307 return false;
3308}
3309
3310/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3311/// If so, insert the new bswap intrinsic and return it.
3312Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3313 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3314 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3315 return 0;
3316
3317 /// ByteValues - For each byte of the result, we keep track of which value
3318 /// defines each byte.
3319 std::vector<Value*> ByteValues;
3320 ByteValues.resize(I.getType()->getPrimitiveSize());
3321
3322 // Try to find all the pieces corresponding to the bswap.
3323 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3324 CollectBSwapParts(I.getOperand(1), ByteValues))
3325 return 0;
3326
3327 // Check to see if all of the bytes come from the same value.
3328 Value *V = ByteValues[0];
3329 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3330
3331 // Check to make sure that all of the bytes come from the same value.
3332 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3333 if (ByteValues[i] != V)
3334 return 0;
3335
3336 // If they do then *success* we can turn this into a bswap. Figure out what
3337 // bswap to make it into.
3338 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003339 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003340 if (I.getType() == Type::UShortTy)
3341 FnName = "llvm.bswap.i16";
3342 else if (I.getType() == Type::UIntTy)
3343 FnName = "llvm.bswap.i32";
3344 else if (I.getType() == Type::ULongTy)
3345 FnName = "llvm.bswap.i64";
3346 else
3347 assert(0 && "Unknown integer type!");
3348 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3349
3350 return new CallInst(F, V);
3351}
3352
3353
Chris Lattner113f4f42002-06-25 16:13:24 +00003354Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003355 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003356 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003357
Chris Lattner81a7a232004-10-16 18:11:37 +00003358 if (isa<UndefValue>(Op1))
3359 return ReplaceInstUsesWith(I, // X | undef -> -1
3360 ConstantIntegral::getAllOnesValue(I.getType()));
3361
Chris Lattner5b2edb12006-02-12 08:02:11 +00003362 // or X, X = X
3363 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003364 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003365
Chris Lattner5b2edb12006-02-12 08:02:11 +00003366 // See if we can simplify any instructions used by the instruction whose sole
3367 // purpose is to compute bits we don't care about.
3368 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003369 if (!isa<PackedType>(I.getType()) &&
3370 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003371 KnownZero, KnownOne))
3372 return &I;
3373
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003374 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003375 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003376 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003377 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3378 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003379 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3380 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003381 InsertNewInstBefore(Or, I);
3382 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3383 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003384
Chris Lattnerd4252a72004-07-30 07:50:03 +00003385 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3386 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3387 std::string Op0Name = Op0->getName(); Op0->setName("");
3388 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3389 InsertNewInstBefore(Or, I);
3390 return BinaryOperator::createXor(Or,
3391 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003392 }
Chris Lattner183b3362004-04-09 19:05:30 +00003393
3394 // Try to fold constant and into select arguments.
3395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003397 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003398 if (isa<PHINode>(Op0))
3399 if (Instruction *NV = FoldOpIntoPhi(I))
3400 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003401 }
3402
Chris Lattner330628a2006-01-06 17:59:59 +00003403 Value *A = 0, *B = 0;
3404 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003405
3406 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3407 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3408 return ReplaceInstUsesWith(I, Op1);
3409 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3410 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3411 return ReplaceInstUsesWith(I, Op0);
3412
Chris Lattnerb7845d62006-07-10 20:25:24 +00003413 // (A | B) | C and A | (B | C) -> bswap if possible.
3414 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003415 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003416 match(Op1, m_Or(m_Value(), m_Value())) ||
3417 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3418 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003419 if (Instruction *BSwap = MatchBSwap(I))
3420 return BSwap;
3421 }
3422
Chris Lattnerb62f5082005-05-09 04:58:36 +00003423 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3424 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003425 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003426 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3427 Op0->setName("");
3428 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3429 }
3430
3431 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3432 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003433 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003434 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3435 Op0->setName("");
3436 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3437 }
3438
Chris Lattner15212982005-09-18 03:42:07 +00003439 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003440 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003441 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3442
3443 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3444 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3445
3446
Chris Lattner01f56c62005-09-18 06:02:59 +00003447 // If we have: ((V + N) & C1) | (V & C2)
3448 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3449 // replace with V+N.
3450 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003451 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003452 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003453 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3454 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003455 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003456 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003457 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003458 return ReplaceInstUsesWith(I, A);
3459 }
3460 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003461 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003462 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3463 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003464 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003465 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003466 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003467 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003468 }
3469 }
3470 }
Chris Lattner812aab72003-08-12 19:11:07 +00003471
Chris Lattnerd4252a72004-07-30 07:50:03 +00003472 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3473 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003474 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003475 ConstantIntegral::getAllOnesValue(I.getType()));
3476 } else {
3477 A = 0;
3478 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003479 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003480 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3481 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003482 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003483 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003484
Misha Brukman9c003d82004-07-30 12:50:08 +00003485 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003486 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3487 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3488 I.getName()+".demorgan"), I);
3489 return BinaryOperator::createNot(And);
3490 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003491 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003492
Chris Lattner3ac7c262003-08-13 20:16:26 +00003493 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003494 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003495 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3496 return R;
3497
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003498 Value *LHSVal, *RHSVal;
3499 ConstantInt *LHSCst, *RHSCst;
3500 Instruction::BinaryOps LHSCC, RHSCC;
3501 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3502 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3503 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3504 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003505 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003506 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3507 // Ensure that the larger constant is on the RHS.
3508 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3509 SetCondInst *LHS = cast<SetCondInst>(Op0);
3510 if (cast<ConstantBool>(Cmp)->getValue()) {
3511 std::swap(LHS, RHS);
3512 std::swap(LHSCst, RHSCst);
3513 std::swap(LHSCC, RHSCC);
3514 }
3515
3516 // At this point, we know we have have two setcc instructions
3517 // comparing a value against two constants and or'ing the result
3518 // together. Because of the above check, we know that we only have
3519 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3520 // FoldSetCCLogical check above), that the two constants are not
3521 // equal.
3522 assert(LHSCst != RHSCst && "Compares not folded above?");
3523
3524 switch (LHSCC) {
3525 default: assert(0 && "Unknown integer condition code!");
3526 case Instruction::SetEQ:
3527 switch (RHSCC) {
3528 default: assert(0 && "Unknown integer condition code!");
3529 case Instruction::SetEQ:
3530 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3531 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3532 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3533 LHSVal->getName()+".off");
3534 InsertNewInstBefore(Add, I);
3535 const Type *UnsType = Add->getType()->getUnsignedVersion();
3536 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3537 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3538 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3539 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3540 }
3541 break; // (X == 13 | X == 15) -> no change
3542
Chris Lattner5c219462005-04-19 06:04:18 +00003543 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3544 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003545 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3546 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3547 return ReplaceInstUsesWith(I, RHS);
3548 }
3549 break;
3550 case Instruction::SetNE:
3551 switch (RHSCC) {
3552 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003553 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3554 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3555 return ReplaceInstUsesWith(I, LHS);
3556 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003557 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003558 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003559 }
3560 break;
3561 case Instruction::SetLT:
3562 switch (RHSCC) {
3563 default: assert(0 && "Unknown integer condition code!");
3564 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3565 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003566 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3567 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003568 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3569 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3570 return ReplaceInstUsesWith(I, RHS);
3571 }
3572 break;
3573 case Instruction::SetGT:
3574 switch (RHSCC) {
3575 default: assert(0 && "Unknown integer condition code!");
3576 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3577 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3578 return ReplaceInstUsesWith(I, LHS);
3579 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3580 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003581 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003582 }
3583 }
3584 }
3585 }
Chris Lattner3af10532006-05-05 06:39:07 +00003586
3587 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3588 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003589 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003590 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003591 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003592 // Only do this if the casts both really cause code to be generated.
3593 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3594 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003595 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3596 Op1C->getOperand(0),
3597 I.getName());
3598 InsertNewInstBefore(NewOp, I);
3599 return new CastInst(NewOp, I.getType());
3600 }
3601 }
3602
Chris Lattner15212982005-09-18 03:42:07 +00003603
Chris Lattner113f4f42002-06-25 16:13:24 +00003604 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003605}
3606
Chris Lattnerc2076352004-02-16 01:20:27 +00003607// XorSelf - Implements: X ^ X --> 0
3608struct XorSelf {
3609 Value *RHS;
3610 XorSelf(Value *rhs) : RHS(rhs) {}
3611 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3612 Instruction *apply(BinaryOperator &Xor) const {
3613 return &Xor;
3614 }
3615};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003616
3617
Chris Lattner113f4f42002-06-25 16:13:24 +00003618Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003619 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003621
Chris Lattner81a7a232004-10-16 18:11:37 +00003622 if (isa<UndefValue>(Op1))
3623 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3624
Chris Lattnerc2076352004-02-16 01:20:27 +00003625 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3626 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3627 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003628 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003629 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003630
3631 // See if we can simplify any instructions used by the instruction whose sole
3632 // purpose is to compute bits we don't care about.
3633 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003634 if (!isa<PackedType>(I.getType()) &&
3635 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003636 KnownZero, KnownOne))
3637 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003638
Chris Lattner97638592003-07-23 21:37:07 +00003639 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003640 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003641 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003642 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003643 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003644 return new SetCondInst(SCI->getInverseCondition(),
3645 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003646
Chris Lattner8f2f5982003-11-05 01:06:05 +00003647 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003648 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3649 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003650 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3651 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003652 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003653 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003654 }
Chris Lattner023a4832004-06-18 06:07:51 +00003655
3656 // ~(~X & Y) --> (X | ~Y)
3657 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3658 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3659 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3660 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003661 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003662 Op0I->getOperand(1)->getName()+".not");
3663 InsertNewInstBefore(NotY, I);
3664 return BinaryOperator::createOr(Op0NotVal, NotY);
3665 }
3666 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003667
Chris Lattner97638592003-07-23 21:37:07 +00003668 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003669 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003670 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003671 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003672 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3673 return BinaryOperator::createSub(
3674 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003675 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003676 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003677 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003678 } else if (Op0I->getOpcode() == Instruction::Or) {
3679 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3680 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3681 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3682 // Anything in both C1 and C2 is known to be zero, remove it from
3683 // NewRHS.
3684 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3685 NewRHS = ConstantExpr::getAnd(NewRHS,
3686 ConstantExpr::getNot(CommonBits));
3687 WorkList.push_back(Op0I);
3688 I.setOperand(0, Op0I->getOperand(0));
3689 I.setOperand(1, NewRHS);
3690 return &I;
3691 }
Chris Lattner97638592003-07-23 21:37:07 +00003692 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003693 }
Chris Lattner183b3362004-04-09 19:05:30 +00003694
3695 // Try to fold constant and into select arguments.
3696 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003697 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003698 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003699 if (isa<PHINode>(Op0))
3700 if (Instruction *NV = FoldOpIntoPhi(I))
3701 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003702 }
3703
Chris Lattnerbb74e222003-03-10 23:06:50 +00003704 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003705 if (X == Op1)
3706 return ReplaceInstUsesWith(I,
3707 ConstantIntegral::getAllOnesValue(I.getType()));
3708
Chris Lattnerbb74e222003-03-10 23:06:50 +00003709 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003710 if (X == Op0)
3711 return ReplaceInstUsesWith(I,
3712 ConstantIntegral::getAllOnesValue(I.getType()));
3713
Chris Lattnerdcd07922006-04-01 08:03:55 +00003714 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003715 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003716 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003717 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003718 I.swapOperands();
3719 std::swap(Op0, Op1);
3720 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003721 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003722 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003723 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003724 } else if (Op1I->getOpcode() == Instruction::Xor) {
3725 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3726 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3727 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3728 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003729 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3730 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3731 Op1I->swapOperands();
3732 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3733 I.swapOperands(); // Simplified below.
3734 std::swap(Op0, Op1);
3735 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003736 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003737
Chris Lattnerdcd07922006-04-01 08:03:55 +00003738 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003739 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003740 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003741 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003742 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003743 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3744 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003745 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003746 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003747 } else if (Op0I->getOpcode() == Instruction::Xor) {
3748 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3749 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3750 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3751 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003752 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3753 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3754 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003755 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3756 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003757 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3758 InsertNewInstBefore(N, I);
3759 return BinaryOperator::createAnd(N, Op1);
3760 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003761 }
3762
Chris Lattner3ac7c262003-08-13 20:16:26 +00003763 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3764 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3765 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3766 return R;
3767
Chris Lattner3af10532006-05-05 06:39:07 +00003768 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3769 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003770 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003771 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003772 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003773 // Only do this if the casts both really cause code to be generated.
3774 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3775 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003776 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3777 Op1C->getOperand(0),
3778 I.getName());
3779 InsertNewInstBefore(NewOp, I);
3780 return new CastInst(NewOp, I.getType());
3781 }
3782 }
3783
Chris Lattner113f4f42002-06-25 16:13:24 +00003784 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003785}
3786
Chris Lattner6862fbd2004-09-29 17:40:11 +00003787static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003788 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003789}
3790
3791/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3792/// overflowed for this type.
3793static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3794 ConstantInt *In2) {
3795 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3796
3797 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003798 return cast<ConstantInt>(Result)->getZExtValue() <
3799 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003800 if (isPositive(In1) != isPositive(In2))
3801 return false;
3802 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003803 return cast<ConstantInt>(Result)->getSExtValue() <
3804 cast<ConstantInt>(In1)->getSExtValue();
3805 return cast<ConstantInt>(Result)->getSExtValue() >
3806 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003807}
3808
Chris Lattner0798af32005-01-13 20:14:25 +00003809/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3810/// code necessary to compute the offset from the base pointer (without adding
3811/// in the base pointer). Return the result as a signed integer of intptr size.
3812static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3813 TargetData &TD = IC.getTargetData();
3814 gep_type_iterator GTI = gep_type_begin(GEP);
3815 const Type *UIntPtrTy = TD.getIntPtrType();
3816 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3817 Value *Result = Constant::getNullValue(SIntPtrTy);
3818
3819 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003820 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003821
Chris Lattner0798af32005-01-13 20:14:25 +00003822 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3823 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003824 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003825 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003826 SIntPtrTy);
3827 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3828 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003829 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003830 Scale = ConstantExpr::getMul(OpC, Scale);
3831 if (Constant *RC = dyn_cast<Constant>(Result))
3832 Result = ConstantExpr::getAdd(RC, Scale);
3833 else {
3834 // Emit an add instruction.
3835 Result = IC.InsertNewInstBefore(
3836 BinaryOperator::createAdd(Result, Scale,
3837 GEP->getName()+".offs"), I);
3838 }
3839 }
3840 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003841 // Convert to correct type.
3842 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3843 Op->getName()+".c"), I);
3844 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003845 // We'll let instcombine(mul) convert this to a shl if possible.
3846 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3847 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003848
3849 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003850 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003851 GEP->getName()+".offs"), I);
3852 }
3853 }
3854 return Result;
3855}
3856
3857/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3858/// else. At this point we know that the GEP is on the LHS of the comparison.
3859Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3860 Instruction::BinaryOps Cond,
3861 Instruction &I) {
3862 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003863
3864 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3865 if (isa<PointerType>(CI->getOperand(0)->getType()))
3866 RHS = CI->getOperand(0);
3867
Chris Lattner0798af32005-01-13 20:14:25 +00003868 Value *PtrBase = GEPLHS->getOperand(0);
3869 if (PtrBase == RHS) {
3870 // As an optimization, we don't actually have to compute the actual value of
3871 // OFFSET if this is a seteq or setne comparison, just return whether each
3872 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003873 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3874 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003875 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3876 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003877 bool EmitIt = true;
3878 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3879 if (isa<UndefValue>(C)) // undef index -> undef.
3880 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3881 if (C->isNullValue())
3882 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003883 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3884 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003885 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003886 return ReplaceInstUsesWith(I, // No comparison is needed here.
3887 ConstantBool::get(Cond == Instruction::SetNE));
3888 }
3889
3890 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003891 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003892 new SetCondInst(Cond, GEPLHS->getOperand(i),
3893 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3894 if (InVal == 0)
3895 InVal = Comp;
3896 else {
3897 InVal = InsertNewInstBefore(InVal, I);
3898 InsertNewInstBefore(Comp, I);
3899 if (Cond == Instruction::SetNE) // True if any are unequal
3900 InVal = BinaryOperator::createOr(InVal, Comp);
3901 else // True if all are equal
3902 InVal = BinaryOperator::createAnd(InVal, Comp);
3903 }
3904 }
3905 }
3906
3907 if (InVal)
3908 return InVal;
3909 else
3910 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3911 ConstantBool::get(Cond == Instruction::SetEQ));
3912 }
Chris Lattner0798af32005-01-13 20:14:25 +00003913
3914 // Only lower this if the setcc is the only user of the GEP or if we expect
3915 // the result to fold to a constant!
3916 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3917 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3918 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3919 return new SetCondInst(Cond, Offset,
3920 Constant::getNullValue(Offset->getType()));
3921 }
3922 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003923 // If the base pointers are different, but the indices are the same, just
3924 // compare the base pointer.
3925 if (PtrBase != GEPRHS->getOperand(0)) {
3926 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003927 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003928 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003929 if (IndicesTheSame)
3930 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3931 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3932 IndicesTheSame = false;
3933 break;
3934 }
3935
3936 // If all indices are the same, just compare the base pointers.
3937 if (IndicesTheSame)
3938 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3939 GEPRHS->getOperand(0));
3940
3941 // Otherwise, the base pointers are different and the indices are
3942 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003943 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003944 }
Chris Lattner0798af32005-01-13 20:14:25 +00003945
Chris Lattner81e84172005-01-13 22:25:21 +00003946 // If one of the GEPs has all zero indices, recurse.
3947 bool AllZeros = true;
3948 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3949 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3950 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3951 AllZeros = false;
3952 break;
3953 }
3954 if (AllZeros)
3955 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3956 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003957
3958 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003959 AllZeros = true;
3960 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3961 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3962 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3963 AllZeros = false;
3964 break;
3965 }
3966 if (AllZeros)
3967 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3968
Chris Lattner4fa89822005-01-14 00:20:05 +00003969 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3970 // If the GEPs only differ by one index, compare it.
3971 unsigned NumDifferences = 0; // Keep track of # differences.
3972 unsigned DiffOperand = 0; // The operand that differs.
3973 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3974 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003975 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3976 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003977 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003978 NumDifferences = 2;
3979 break;
3980 } else {
3981 if (NumDifferences++) break;
3982 DiffOperand = i;
3983 }
3984 }
3985
3986 if (NumDifferences == 0) // SAME GEP?
3987 return ReplaceInstUsesWith(I, // No comparison is needed here.
3988 ConstantBool::get(Cond == Instruction::SetEQ));
3989 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003990 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3991 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003992
3993 // Convert the operands to signed values to make sure to perform a
3994 // signed comparison.
3995 const Type *NewTy = LHSV->getType()->getSignedVersion();
3996 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00003997 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00003998 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00003999 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004000 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004001 }
4002 }
4003
Chris Lattner0798af32005-01-13 20:14:25 +00004004 // Only lower this if the setcc is the only user of the GEP or if we expect
4005 // the result to fold to a constant!
4006 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4007 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4008 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4009 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4010 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4011 return new SetCondInst(Cond, L, R);
4012 }
4013 }
4014 return 0;
4015}
4016
4017
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004018Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004019 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004020 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4021 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004022
4023 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004024 if (Op0 == Op1)
4025 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004026
Chris Lattner81a7a232004-10-16 18:11:37 +00004027 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4028 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4029
Chris Lattner15ff1e12004-11-14 07:33:16 +00004030 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4031 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004032 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4033 isa<ConstantPointerNull>(Op0)) &&
4034 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004035 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004036 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4037
4038 // setcc's with boolean values can always be turned into bitwise operations
4039 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004040 switch (I.getOpcode()) {
4041 default: assert(0 && "Invalid setcc instruction!");
4042 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004043 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004044 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004045 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004046 }
Chris Lattner4456da62004-08-11 00:50:51 +00004047 case Instruction::SetNE:
4048 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004049
Chris Lattner4456da62004-08-11 00:50:51 +00004050 case Instruction::SetGT:
4051 std::swap(Op0, Op1); // Change setgt -> setlt
4052 // FALL THROUGH
4053 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4054 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4055 InsertNewInstBefore(Not, I);
4056 return BinaryOperator::createAnd(Not, Op1);
4057 }
4058 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004059 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004060 // FALL THROUGH
4061 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4062 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4063 InsertNewInstBefore(Not, I);
4064 return BinaryOperator::createOr(Not, Op1);
4065 }
4066 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004067 }
4068
Chris Lattner2dd01742004-06-09 04:24:29 +00004069 // See if we are doing a comparison between a constant and an instruction that
4070 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004071 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004072 // Check to see if we are comparing against the minimum or maximum value...
4073 if (CI->isMinValue()) {
4074 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004075 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004076 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004077 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004078 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4079 return BinaryOperator::createSetEQ(Op0, Op1);
4080 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4081 return BinaryOperator::createSetNE(Op0, Op1);
4082
4083 } else if (CI->isMaxValue()) {
4084 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004085 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004086 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004087 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004088 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4089 return BinaryOperator::createSetEQ(Op0, Op1);
4090 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4091 return BinaryOperator::createSetNE(Op0, Op1);
4092
4093 // Comparing against a value really close to min or max?
4094 } else if (isMinValuePlusOne(CI)) {
4095 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4096 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4097 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4098 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4099
4100 } else if (isMaxValueMinusOne(CI)) {
4101 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4102 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4103 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4104 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4105 }
4106
4107 // If we still have a setle or setge instruction, turn it into the
4108 // appropriate setlt or setgt instruction. Since the border cases have
4109 // already been handled above, this requires little checking.
4110 //
4111 if (I.getOpcode() == Instruction::SetLE)
4112 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4113 if (I.getOpcode() == Instruction::SetGE)
4114 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4115
Chris Lattneree0f2802006-02-12 02:07:56 +00004116
4117 // See if we can fold the comparison based on bits known to be zero or one
4118 // in the input.
4119 uint64_t KnownZero, KnownOne;
4120 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4121 KnownZero, KnownOne, 0))
4122 return &I;
4123
4124 // Given the known and unknown bits, compute a range that the LHS could be
4125 // in.
4126 if (KnownOne | KnownZero) {
4127 if (Ty->isUnsigned()) { // Unsigned comparison.
4128 uint64_t Min, Max;
4129 uint64_t RHSVal = CI->getZExtValue();
4130 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4131 Min, Max);
4132 switch (I.getOpcode()) { // LE/GE have been folded already.
4133 default: assert(0 && "Unknown setcc opcode!");
4134 case Instruction::SetEQ:
4135 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004136 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004137 break;
4138 case Instruction::SetNE:
4139 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004140 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004141 break;
4142 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004143 if (Max < RHSVal)
4144 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4145 if (Min > RHSVal)
4146 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004147 break;
4148 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004149 if (Min > RHSVal)
4150 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4151 if (Max < RHSVal)
4152 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004153 break;
4154 }
4155 } else { // Signed comparison.
4156 int64_t Min, Max;
4157 int64_t RHSVal = CI->getSExtValue();
4158 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4159 Min, Max);
4160 switch (I.getOpcode()) { // LE/GE have been folded already.
4161 default: assert(0 && "Unknown setcc opcode!");
4162 case Instruction::SetEQ:
4163 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004164 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004165 break;
4166 case Instruction::SetNE:
4167 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004168 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004169 break;
4170 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004171 if (Max < RHSVal)
4172 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4173 if (Min > RHSVal)
4174 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004175 break;
4176 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004177 if (Min > RHSVal)
4178 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4179 if (Max < RHSVal)
4180 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004181 break;
4182 }
4183 }
4184 }
4185
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004186 // Since the RHS is a constantInt (CI), if the left hand side is an
4187 // instruction, see if that instruction also has constants so that the
4188 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004189 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004190 switch (LHSI->getOpcode()) {
4191 case Instruction::And:
4192 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4193 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004194 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4195
4196 // If an operand is an AND of a truncating cast, we can widen the
4197 // and/compare to be the input width without changing the value
4198 // produced, eliminating a cast.
4199 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4200 // We can do this transformation if either the AND constant does not
4201 // have its sign bit set or if it is an equality comparison.
4202 // Extending a relational comparison when we're checking the sign
4203 // bit would not work.
4204 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4205 (I.isEquality() ||
4206 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4207 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4208 ConstantInt *NewCST;
4209 ConstantInt *NewCI;
4210 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004211 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004212 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004213 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004214 CI->getZExtValue());
4215 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004216 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004217 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004218 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004219 CI->getZExtValue());
4220 }
4221 Instruction *NewAnd =
4222 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4223 LHSI->getName());
4224 InsertNewInstBefore(NewAnd, I);
4225 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4226 }
4227 }
4228
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004229 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4230 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4231 // happens a LOT in code produced by the C front-end, for bitfield
4232 // access.
4233 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004234
4235 // Check to see if there is a noop-cast between the shift and the and.
4236 if (!Shift) {
4237 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4238 if (CI->getOperand(0)->getType()->isIntegral() &&
4239 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4240 CI->getType()->getPrimitiveSizeInBits())
4241 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4242 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004243
Reid Spencere0fc4df2006-10-20 07:07:24 +00004244 ConstantInt *ShAmt;
4245 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004246 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4247 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004248
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004249 // We can fold this as long as we can't shift unknown bits
4250 // into the mask. This can only happen with signed shift
4251 // rights, as they sign-extend.
4252 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004253 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004254 if (!CanFold) {
4255 // To test for the bad case of the signed shr, see if any
4256 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004257 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004258 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4259
Reid Spencere0fc4df2006-10-20 07:07:24 +00004260 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004261 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004262 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4263 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004264 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4265 CanFold = true;
4266 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004267
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004268 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004269 Constant *NewCst;
4270 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004271 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004272 else
4273 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004274
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004275 // Check to see if we are shifting out any of the bits being
4276 // compared.
4277 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4278 // If we shifted bits out, the fold is not going to work out.
4279 // As a special case, check to see if this means that the
4280 // result is always true or false now.
4281 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004282 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004283 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004284 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004285 } else {
4286 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004287 Constant *NewAndCST;
4288 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004289 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004290 else
4291 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4292 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004293 if (AndTy == Ty)
4294 LHSI->setOperand(0, Shift->getOperand(0));
4295 else {
4296 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4297 *Shift);
4298 LHSI->setOperand(0, NewCast);
4299 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004300 WorkList.push_back(Shift); // Shift is dead.
4301 AddUsesToWorkList(I);
4302 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004303 }
4304 }
Chris Lattner35167c32004-06-09 07:59:58 +00004305 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004306
4307 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4308 // preferable because it allows the C<<Y expression to be hoisted out
4309 // of a loop if Y is invariant and X is not.
4310 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004311 I.isEquality() && !Shift->isArithmeticShift() &&
4312 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004313 // Compute C << Y.
4314 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004315 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004316 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4317 "tmp");
4318 } else {
4319 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004320 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004321 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004322 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004323 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004324 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004325 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004326 }
4327 InsertNewInstBefore(cast<Instruction>(NS), I);
4328
4329 // If C's sign doesn't agree with the and, insert a cast now.
4330 if (NS->getType() != LHSI->getType())
4331 NS = InsertCastBefore(NS, LHSI->getType(), I);
4332
4333 Value *ShiftOp = Shift->getOperand(0);
4334 if (ShiftOp->getType() != LHSI->getType())
4335 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4336
4337 // Compute X & (C << Y).
4338 Instruction *NewAnd =
4339 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4340 InsertNewInstBefore(NewAnd, I);
4341
4342 I.setOperand(0, NewAnd);
4343 return &I;
4344 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004345 }
4346 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004347
Chris Lattner272d5ca2004-09-28 18:22:15 +00004348 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004349 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004350 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004351 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4352
4353 // Check that the shift amount is in range. If not, don't perform
4354 // undefined shifts. When the shift is visited it will be
4355 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004356 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004357 break;
4358
Chris Lattner272d5ca2004-09-28 18:22:15 +00004359 // If we are comparing against bits always shifted out, the
4360 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004361 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004362 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004363 if (Comp != CI) {// Comparing against a bit that we know is zero.
4364 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4365 Constant *Cst = ConstantBool::get(IsSetNE);
4366 return ReplaceInstUsesWith(I, Cst);
4367 }
4368
4369 if (LHSI->hasOneUse()) {
4370 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004371 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004372 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4373
4374 Constant *Mask;
4375 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004376 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004377 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004378 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004379 } else {
4380 Mask = ConstantInt::getAllOnesValue(CI->getType());
4381 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004382
Chris Lattner272d5ca2004-09-28 18:22:15 +00004383 Instruction *AndI =
4384 BinaryOperator::createAnd(LHSI->getOperand(0),
4385 Mask, LHSI->getName()+".mask");
4386 Value *And = InsertNewInstBefore(AndI, I);
4387 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004388 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004389 }
4390 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004391 }
4392 break;
4393
Reid Spencerfdff9382006-11-08 06:47:33 +00004394 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4395 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004396 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004397 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004398 // Check that the shift amount is in range. If not, don't perform
4399 // undefined shifts. When the shift is visited it will be
4400 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004401 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004402 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004403 break;
4404
Chris Lattner1023b872004-09-27 16:18:50 +00004405 // If we are comparing against bits always shifted out, the
4406 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004407 Constant *Comp;
4408 if (CI->getType()->isUnsigned())
4409 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4410 ShAmt);
4411 else
4412 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4413 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004414
Chris Lattner1023b872004-09-27 16:18:50 +00004415 if (Comp != CI) {// Comparing against a bit that we know is zero.
4416 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4417 Constant *Cst = ConstantBool::get(IsSetNE);
4418 return ReplaceInstUsesWith(I, Cst);
4419 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004420
Chris Lattner1023b872004-09-27 16:18:50 +00004421 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004422 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004423
Chris Lattner1023b872004-09-27 16:18:50 +00004424 // Otherwise strength reduce the shift into an and.
4425 uint64_t Val = ~0ULL; // All ones.
4426 Val <<= ShAmtVal; // Shift over to the right spot.
4427
4428 Constant *Mask;
4429 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004430 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004431 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004432 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004433 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004434 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004435
Chris Lattner1023b872004-09-27 16:18:50 +00004436 Instruction *AndI =
4437 BinaryOperator::createAnd(LHSI->getOperand(0),
4438 Mask, LHSI->getName()+".mask");
4439 Value *And = InsertNewInstBefore(AndI, I);
4440 return new SetCondInst(I.getOpcode(), And,
4441 ConstantExpr::getShl(CI, ShAmt));
4442 }
Chris Lattner1023b872004-09-27 16:18:50 +00004443 }
4444 }
4445 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004446
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004447 case Instruction::SDiv:
4448 case Instruction::UDiv:
4449 // Fold: setcc ([us]div X, C1), C2 -> range test
4450 // Fold this div into the comparison, producing a range check.
4451 // Determine, based on the divide type, what the range is being
4452 // checked. If there is an overflow on the low or high side, remember
4453 // it, otherwise compute the range [low, hi) bounding the new value.
4454 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004455 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004456 // FIXME: If the operand types don't match the type of the divide
4457 // then don't attempt this transform. The code below doesn't have the
4458 // logic to deal with a signed divide and an unsigned compare (and
4459 // vice versa). This is because (x /s C1) <s C2 produces different
4460 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4461 // (x /u C1) <u C2. Simply casting the operands and result won't
4462 // work. :( The if statement below tests that condition and bails
4463 // if it finds it.
4464 const Type* DivRHSTy = DivRHS->getType();
4465 unsigned DivOpCode = LHSI->getOpcode();
4466 if (I.isEquality() &&
4467 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4468 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4469 break;
4470
4471 // Initialize the variables that will indicate the nature of the
4472 // range check.
4473 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004474 ConstantInt *LoBound = 0, *HiBound = 0;
4475
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004476 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4477 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4478 // C2 (CI). By solving for X we can turn this into a range check
4479 // instead of computing a divide.
4480 ConstantInt *Prod =
4481 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004482
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004483 // Determine if the product overflows by seeing if the product is
4484 // not equal to the divide. Make sure we do the same kind of divide
4485 // as in the LHS instruction that we're folding.
4486 bool ProdOV = !DivRHS->isNullValue() &&
4487 (DivOpCode == Instruction::SDiv ?
4488 ConstantExpr::getSDiv(Prod, DivRHS) :
4489 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4490
4491 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004492 Instruction::BinaryOps Opcode = I.getOpcode();
4493
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004494 if (DivRHS->isNullValue()) {
4495 // Don't hack on divide by zeros!
4496 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004497 LoBound = Prod;
4498 LoOverflow = ProdOV;
4499 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004500 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004501 if (CI->isNullValue()) { // (X / pos) op 0
4502 // Can't overflow.
4503 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4504 HiBound = DivRHS;
4505 } else if (isPositive(CI)) { // (X / pos) op pos
4506 LoBound = Prod;
4507 LoOverflow = ProdOV;
4508 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4509 } else { // (X / pos) op neg
4510 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4511 LoOverflow = AddWithOverflow(LoBound, Prod,
4512 cast<ConstantInt>(DivRHSH));
4513 HiBound = Prod;
4514 HiOverflow = ProdOV;
4515 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004516 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004517 if (CI->isNullValue()) { // (X / neg) op 0
4518 LoBound = AddOne(DivRHS);
4519 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004520 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004521 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004522 } else if (isPositive(CI)) { // (X / neg) op pos
4523 HiOverflow = LoOverflow = ProdOV;
4524 if (!LoOverflow)
4525 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4526 HiBound = AddOne(Prod);
4527 } else { // (X / neg) op neg
4528 LoBound = Prod;
4529 LoOverflow = HiOverflow = ProdOV;
4530 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4531 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004532
Chris Lattnera92af962004-10-11 19:40:04 +00004533 // Dividing by a negate swaps the condition.
4534 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004535 }
4536
4537 if (LoBound) {
4538 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004539 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004540 default: assert(0 && "Unhandled setcc opcode!");
4541 case Instruction::SetEQ:
4542 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004543 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004544 else if (HiOverflow)
4545 return new SetCondInst(Instruction::SetGE, X, LoBound);
4546 else if (LoOverflow)
4547 return new SetCondInst(Instruction::SetLT, X, HiBound);
4548 else
4549 return InsertRangeTest(X, LoBound, HiBound, true, I);
4550 case Instruction::SetNE:
4551 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004552 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004553 else if (HiOverflow)
4554 return new SetCondInst(Instruction::SetLT, X, LoBound);
4555 else if (LoOverflow)
4556 return new SetCondInst(Instruction::SetGE, X, HiBound);
4557 else
4558 return InsertRangeTest(X, LoBound, HiBound, false, I);
4559 case Instruction::SetLT:
4560 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004561 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004562 return new SetCondInst(Instruction::SetLT, X, LoBound);
4563 case Instruction::SetGT:
4564 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004565 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004566 return new SetCondInst(Instruction::SetGE, X, HiBound);
4567 }
4568 }
4569 }
4570 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004571 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004572
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004573 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004574 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004575 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4576
Reid Spencere0fc4df2006-10-20 07:07:24 +00004577 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4578 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004579 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4580 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004581 case Instruction::SRem:
4582 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4583 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4584 BO->hasOneUse()) {
4585 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4586 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004587 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4588 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004589 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004590 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004591 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004592 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004593 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004594 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004595 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4596 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004597 if (BO->hasOneUse())
4598 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4599 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004600 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004601 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4602 // efficiently invertible, or if the add has just this one use.
4603 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004604
Chris Lattnerc992add2003-08-13 05:33:12 +00004605 if (Value *NegVal = dyn_castNegVal(BOp1))
4606 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4607 else if (Value *NegVal = dyn_castNegVal(BOp0))
4608 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004609 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004610 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4611 BO->setName("");
4612 InsertNewInstBefore(Neg, I);
4613 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4614 }
4615 }
4616 break;
4617 case Instruction::Xor:
4618 // For the xor case, we can xor two constants together, eliminating
4619 // the explicit xor.
4620 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4621 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004622 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004623
4624 // FALLTHROUGH
4625 case Instruction::Sub:
4626 // Replace (([sub|xor] A, B) != 0) with (A != B)
4627 if (CI->isNullValue())
4628 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4629 BO->getOperand(1));
4630 break;
4631
4632 case Instruction::Or:
4633 // If bits are being or'd in that are not present in the constant we
4634 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004635 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004636 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004637 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004638 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004639 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004640 break;
4641
4642 case Instruction::And:
4643 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004644 // If bits are being compared against that are and'd out, then the
4645 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004646 if (!ConstantExpr::getAnd(CI,
4647 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004648 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004649
Chris Lattner35167c32004-06-09 07:59:58 +00004650 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004651 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004652 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4653 Instruction::SetNE, Op0,
4654 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004655
Chris Lattnerc992add2003-08-13 05:33:12 +00004656 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4657 // to be a signed value as appropriate.
4658 if (isSignBit(BOC)) {
4659 Value *X = BO->getOperand(0);
4660 // If 'X' is not signed, insert a cast now...
4661 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004662 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004663 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004664 }
4665 return new SetCondInst(isSetNE ? Instruction::SetLT :
4666 Instruction::SetGE, X,
4667 Constant::getNullValue(X->getType()));
4668 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004669
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004670 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004671 if (CI->isNullValue() && isHighOnes(BOC)) {
4672 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004673 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004674
4675 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004676 if (NegX->getType()->isSigned()) {
4677 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4678 X = InsertCastBefore(X, DestTy, I);
4679 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004680 }
4681
4682 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004683 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004684 }
4685
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004686 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004687 default: break;
4688 }
4689 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004690 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004691 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004692 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4693 Value *CastOp = Cast->getOperand(0);
4694 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004695 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004696 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004697 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004698 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004699 "Source and destination signednesses should differ!");
4700 if (Cast->getType()->isSigned()) {
4701 // If this is a signed comparison, check for comparisons in the
4702 // vicinity of zero.
4703 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4704 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004705 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004706 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004707 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004708 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004709 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004710 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004711 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004712 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004713 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004714 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004715 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004716 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004717 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004718 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004719 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004720 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004721 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004722 return BinaryOperator::createSetLT(CastOp,
4723 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004724 }
4725 }
4726 }
Chris Lattnere967b342003-06-04 05:10:11 +00004727 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004728 }
4729
Chris Lattner77c32c32005-04-23 15:31:55 +00004730 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4731 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4732 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4733 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004734 case Instruction::GetElementPtr:
4735 if (RHSC->isNullValue()) {
4736 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4737 bool isAllZeros = true;
4738 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4739 if (!isa<Constant>(LHSI->getOperand(i)) ||
4740 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4741 isAllZeros = false;
4742 break;
4743 }
4744 if (isAllZeros)
4745 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4746 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4747 }
4748 break;
4749
Chris Lattner77c32c32005-04-23 15:31:55 +00004750 case Instruction::PHI:
4751 if (Instruction *NV = FoldOpIntoPhi(I))
4752 return NV;
4753 break;
4754 case Instruction::Select:
4755 // If either operand of the select is a constant, we can fold the
4756 // comparison into the select arms, which will cause one to be
4757 // constant folded and the select turned into a bitwise or.
4758 Value *Op1 = 0, *Op2 = 0;
4759 if (LHSI->hasOneUse()) {
4760 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4761 // Fold the known value into the constant operand.
4762 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4763 // Insert a new SetCC of the other select operand.
4764 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4765 LHSI->getOperand(2), RHSC,
4766 I.getName()), I);
4767 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4768 // Fold the known value into the constant operand.
4769 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4770 // Insert a new SetCC of the other select operand.
4771 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4772 LHSI->getOperand(1), RHSC,
4773 I.getName()), I);
4774 }
4775 }
Jeff Cohen82639852005-04-23 21:38:35 +00004776
Chris Lattner77c32c32005-04-23 15:31:55 +00004777 if (Op1)
4778 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4779 break;
4780 }
4781 }
4782
Chris Lattner0798af32005-01-13 20:14:25 +00004783 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4784 if (User *GEP = dyn_castGetElementPtr(Op0))
4785 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4786 return NI;
4787 if (User *GEP = dyn_castGetElementPtr(Op1))
4788 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4789 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4790 return NI;
4791
Chris Lattner16930792003-11-03 04:25:02 +00004792 // Test to see if the operands of the setcc are casted versions of other
4793 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004794 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4795 Value *CastOp0 = CI->getOperand(0);
4796 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004797 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004798 // We keep moving the cast from the left operand over to the right
4799 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004800 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004801
Chris Lattner16930792003-11-03 04:25:02 +00004802 // If operand #1 is a cast instruction, see if we can eliminate it as
4803 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004804 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4805 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004806 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004807 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004808
Chris Lattner16930792003-11-03 04:25:02 +00004809 // If Op1 is a constant, we can fold the cast into the constant.
4810 if (Op1->getType() != Op0->getType())
4811 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4812 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4813 } else {
4814 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004815 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004816 }
4817 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4818 }
4819
Chris Lattner6444c372003-11-03 05:17:03 +00004820 // Handle the special case of: setcc (cast bool to X), <cst>
4821 // This comes up when you have code like
4822 // int X = A < B;
4823 // if (X) ...
4824 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004825 // with a constant or another cast from the same type.
4826 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4827 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4828 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004829 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004830
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004831 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004832 Value *A, *B;
4833 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4834 (A == Op1 || B == Op1)) {
4835 // (A^B) == A -> B == 0
4836 Value *OtherVal = A == Op1 ? B : A;
4837 return BinaryOperator::create(I.getOpcode(), OtherVal,
4838 Constant::getNullValue(A->getType()));
4839 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4840 (A == Op0 || B == Op0)) {
4841 // A == (A^B) -> B == 0
4842 Value *OtherVal = A == Op0 ? B : A;
4843 return BinaryOperator::create(I.getOpcode(), OtherVal,
4844 Constant::getNullValue(A->getType()));
4845 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4846 // (A-B) == A -> B == 0
4847 return BinaryOperator::create(I.getOpcode(), B,
4848 Constant::getNullValue(B->getType()));
4849 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4850 // A == (A-B) -> B == 0
4851 return BinaryOperator::create(I.getOpcode(), B,
4852 Constant::getNullValue(B->getType()));
4853 }
4854 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004855 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004856}
4857
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004858// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4859// We only handle extending casts so far.
4860//
4861Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4862 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4863 const Type *SrcTy = LHSCIOp->getType();
4864 const Type *DestTy = SCI.getOperand(0)->getType();
4865 Value *RHSCIOp;
4866
4867 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004868 return 0;
4869
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004870 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4871 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4872 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4873
4874 // Is this a sign or zero extension?
4875 bool isSignSrc = SrcTy->isSigned();
4876 bool isSignDest = DestTy->isSigned();
4877
4878 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4879 // Not an extension from the same type?
4880 RHSCIOp = CI->getOperand(0);
4881 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4882 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4883 // Compute the constant that would happen if we truncated to SrcTy then
4884 // reextended to DestTy.
4885 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4886
4887 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00004888 // Make sure that src sign and dest sign match. For example,
4889 //
4890 // %A = cast short %X to uint
4891 // %B = setgt uint %A, 1330
4892 //
Devang Patel88afd002006-10-19 19:21:36 +00004893 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00004894 //
4895 // %B = setgt short %X, 1330
4896 //
4897 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00004898 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4899 // OR operation is EQ/NE.
4900 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00004901 RHSCIOp = Res;
4902 else
4903 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004904 } else {
4905 // If the value cannot be represented in the shorter type, we cannot emit
4906 // a simple comparison.
4907 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004908 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004909 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004910 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004911
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004912 // Evaluate the comparison for LT.
4913 Value *Result;
4914 if (DestTy->isSigned()) {
4915 // We're performing a signed comparison.
4916 if (isSignSrc) {
4917 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004918 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004919 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004920 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00004921 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004922 } else {
4923 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004924 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004925 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004926 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004927 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004928 }
4929 } else {
4930 // We're performing an unsigned comparison.
4931 if (!isSignSrc) {
4932 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004933 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004934 } else {
4935 // We're performing an unsigned comp with a sign extended value.
4936 // This is true if the input is >= 0. [aka >s -1]
4937 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4938 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4939 NegOne, SCI.getName()), SCI);
4940 }
Reid Spencer279fa252004-11-28 21:31:15 +00004941 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004942
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004943 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004944 if (SCI.getOpcode() == Instruction::SetLT) {
4945 return ReplaceInstUsesWith(SCI, Result);
4946 } else {
4947 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4948 if (Constant *CI = dyn_cast<Constant>(Result))
4949 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4950 else
4951 return BinaryOperator::createNot(Result);
4952 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004953 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004954 } else {
4955 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004956 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004957
Chris Lattner252a8452005-06-16 03:00:08 +00004958 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004959 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4960}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004961
Chris Lattnere8d6c602003-03-10 19:16:08 +00004962Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004963 assert(I.getOperand(1)->getType() == Type::UByteTy);
4964 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004965 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004966
4967 // shl X, 0 == X and shr X, 0 == X
4968 // shl 0, X == 0 and shr 0, X == 0
4969 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004970 Op0 == Constant::getNullValue(Op0->getType()))
4971 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004972
Chris Lattner81a7a232004-10-16 18:11:37 +00004973 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4974 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004975 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004976 else // undef << X -> 0 AND undef >>u X -> 0
4977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4978 }
4979 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004980 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004981 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4982 else
4983 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4984 }
4985
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004986 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4987 if (!isLeftShift)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004988 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner5dee3b22006-10-20 18:20:21 +00004989 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004990 return ReplaceInstUsesWith(I, CSI);
4991
Chris Lattner183b3362004-04-09 19:05:30 +00004992 // Try to fold constant and into select arguments.
4993 if (isa<Constant>(Op0))
4994 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004995 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004996 return R;
4997
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004998 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004999 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005000 if (MaskedValueIsZero(Op0,
5001 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005002 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005003 }
5004 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005005
Reid Spencere0fc4df2006-10-20 07:07:24 +00005006 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5007 if (CUI->getType()->isUnsigned())
5008 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5009 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005010 return 0;
5011}
5012
Reid Spencere0fc4df2006-10-20 07:07:24 +00005013Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005014 ShiftInst &I) {
5015 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005016 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5017 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005018 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005019
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005020 // See if we can simplify any instructions used by the instruction whose sole
5021 // purpose is to compute bits we don't care about.
5022 uint64_t KnownZero, KnownOne;
5023 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5024 KnownZero, KnownOne))
5025 return &I;
5026
Chris Lattner14553932006-01-06 07:12:35 +00005027 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5028 // of a signed value.
5029 //
5030 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005031 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005032 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005033 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5034 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005035 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005036 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005037 }
Chris Lattner14553932006-01-06 07:12:35 +00005038 }
5039
5040 // ((X*C1) << C2) == (X * (C1 << C2))
5041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5042 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5043 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5044 return BinaryOperator::createMul(BO->getOperand(0),
5045 ConstantExpr::getShl(BOOp, Op1));
5046
5047 // Try to fold constant and into select arguments.
5048 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5049 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5050 return R;
5051 if (isa<PHINode>(Op0))
5052 if (Instruction *NV = FoldOpIntoPhi(I))
5053 return NV;
5054
5055 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005056 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5057 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5058 Value *V1, *V2;
5059 ConstantInt *CC;
5060 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005061 default: break;
5062 case Instruction::Add:
5063 case Instruction::And:
5064 case Instruction::Or:
5065 case Instruction::Xor:
5066 // These operators commute.
5067 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005068 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5069 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005070 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005071 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005072 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005073 Op0BO->getName());
5074 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005075 Instruction *X =
5076 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5077 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005078 InsertNewInstBefore(X, I); // (X + (Y << C))
5079 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005080 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005081 return BinaryOperator::createAnd(X, C2);
5082 }
Chris Lattner14553932006-01-06 07:12:35 +00005083
Chris Lattner797dee72005-09-18 06:30:59 +00005084 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5085 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5086 match(Op0BO->getOperand(1),
5087 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005088 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005089 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005090 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005091 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005092 Op0BO->getName());
5093 InsertNewInstBefore(YS, I); // (Y << C)
5094 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005095 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005096 V1->getName()+".mask");
5097 InsertNewInstBefore(XM, I); // X & (CC << C)
5098
5099 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5100 }
Chris Lattner14553932006-01-06 07:12:35 +00005101
Chris Lattner797dee72005-09-18 06:30:59 +00005102 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005103 case Instruction::Sub:
5104 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005105 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5106 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005107 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005108 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005109 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005110 Op0BO->getName());
5111 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005112 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005113 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005114 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005115 InsertNewInstBefore(X, I); // (X + (Y << C))
5116 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005117 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005118 return BinaryOperator::createAnd(X, C2);
5119 }
Chris Lattner14553932006-01-06 07:12:35 +00005120
Chris Lattner1df0e982006-05-31 21:14:00 +00005121 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005122 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5123 match(Op0BO->getOperand(0),
5124 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005125 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005126 cast<BinaryOperator>(Op0BO->getOperand(0))
5127 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005128 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005129 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005130 Op0BO->getName());
5131 InsertNewInstBefore(YS, I); // (Y << C)
5132 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005133 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005134 V1->getName()+".mask");
5135 InsertNewInstBefore(XM, I); // X & (CC << C)
5136
Chris Lattner1df0e982006-05-31 21:14:00 +00005137 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005138 }
Chris Lattner14553932006-01-06 07:12:35 +00005139
Chris Lattner27cb9db2005-09-18 05:12:10 +00005140 break;
Chris Lattner14553932006-01-06 07:12:35 +00005141 }
5142
5143
5144 // If the operand is an bitwise operator with a constant RHS, and the
5145 // shift is the only use, we can pull it out of the shift.
5146 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5147 bool isValid = true; // Valid only for And, Or, Xor
5148 bool highBitSet = false; // Transform if high bit of constant set?
5149
5150 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005151 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005152 case Instruction::Add:
5153 isValid = isLeftShift;
5154 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005155 case Instruction::Or:
5156 case Instruction::Xor:
5157 highBitSet = false;
5158 break;
5159 case Instruction::And:
5160 highBitSet = true;
5161 break;
Chris Lattner14553932006-01-06 07:12:35 +00005162 }
5163
5164 // If this is a signed shift right, and the high bit is modified
5165 // by the logical operation, do not perform the transformation.
5166 // The highBitSet boolean indicates the value of the high bit of
5167 // the constant which would cause it to be modified for this
5168 // operation.
5169 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005170 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005171 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005172 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5173 }
5174
5175 if (isValid) {
5176 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5177
5178 Instruction *NewShift =
5179 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5180 Op0BO->getName());
5181 Op0BO->setName("");
5182 InsertNewInstBefore(NewShift, I);
5183
5184 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5185 NewRHS);
5186 }
5187 }
5188 }
5189 }
5190
Chris Lattnereb372a02006-01-06 07:52:12 +00005191 // Find out if this is a shift of a shift by a constant.
5192 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005193 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005194 ShiftOp = Op0SI;
5195 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5196 // If this is a noop-integer case of a shift instruction, use the shift.
5197 if (CI->getOperand(0)->getType()->isInteger() &&
5198 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5199 CI->getType()->getPrimitiveSizeInBits() &&
5200 isa<ShiftInst>(CI->getOperand(0))) {
5201 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5202 }
5203 }
5204
Reid Spencere0fc4df2006-10-20 07:07:24 +00005205 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005206 // Find the operands and properties of the input shift. Note that the
5207 // signedness of the input shift may differ from the current shift if there
5208 // is a noop cast between the two.
5209 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005210 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5211 ShiftOp->getType()->isSigned() :
5212 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005213 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005214
Reid Spencere0fc4df2006-10-20 07:07:24 +00005215 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005216
Reid Spencere0fc4df2006-10-20 07:07:24 +00005217 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5218 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005219
5220 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5221 if (isLeftShift == isShiftOfLeftShift) {
5222 // Do not fold these shifts if the first one is signed and the second one
5223 // is unsigned and this is a right shift. Further, don't do any folding
5224 // on them.
5225 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5226 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005227
Chris Lattnereb372a02006-01-06 07:52:12 +00005228 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5229 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5230 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005231
Chris Lattnereb372a02006-01-06 07:52:12 +00005232 Value *Op = ShiftOp->getOperand(0);
5233 if (isShiftOfSignedShift != isSignedShift)
5234 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
Reid Spencerfdff9382006-11-08 06:47:33 +00005235 ShiftInst* ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005236 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005237 if (I.getType() == ShiftResult->getType())
5238 return ShiftResult;
5239 InsertNewInstBefore(ShiftResult, I);
5240 return new CastInst(ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005241 }
5242
5243 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5244 // signed types, we can only support the (A >> c1) << c2 configuration,
5245 // because it can not turn an arbitrary bit of A into a sign bit.
5246 if (isUnsignedShift || isLeftShift) {
5247 // Calculate bitmask for what gets shifted off the edge.
5248 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5249 if (isLeftShift)
5250 C = ConstantExpr::getShl(C, ShiftAmt1C);
5251 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005252 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005253
5254 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005255 if (Op->getType() != C->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00005256 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005257
5258 Instruction *Mask =
5259 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5260 InsertNewInstBefore(Mask, I);
5261
5262 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005263 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005264 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005265 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005266 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005267 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005268 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5269 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005270 return new ShiftInst(Instruction::LShr, Mask,
5271 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005272 } else {
5273 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005274 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005275 }
5276 } else {
5277 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005278 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005279 Instruction *Shift =
5280 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005281 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005282 InsertNewInstBefore(Shift, I);
5283
5284 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5285 C = ConstantExpr::getShl(C, Op1);
5286 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5287 InsertNewInstBefore(Mask, I);
5288 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005289 }
5290 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005291 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005292 // this case, C1 == C2 and C1 is 8, 16, or 32.
5293 if (ShiftAmt1 == ShiftAmt2) {
5294 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005295 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005296 case 8 : SExtType = Type::SByteTy; break;
5297 case 16: SExtType = Type::ShortTy; break;
5298 case 32: SExtType = Type::IntTy; break;
5299 }
5300
5301 if (SExtType) {
5302 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5303 SExtType, "sext");
5304 InsertNewInstBefore(NewTrunc, I);
5305 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005306 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005307 }
Chris Lattner86102b82005-01-01 16:22:27 +00005308 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005309 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005310 return 0;
5311}
5312
Chris Lattner48a44f72002-05-02 17:06:02 +00005313
Chris Lattner8f663e82005-10-29 04:36:15 +00005314/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5315/// expression. If so, decompose it, returning some value X, such that Val is
5316/// X*Scale+Offset.
5317///
5318static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5319 unsigned &Offset) {
5320 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5322 if (CI->getType()->isUnsigned()) {
5323 Offset = CI->getZExtValue();
5324 Scale = 1;
5325 return ConstantInt::get(Type::UIntTy, 0);
5326 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005327 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5328 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005329 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5330 if (CUI->getType()->isUnsigned()) {
5331 if (I->getOpcode() == Instruction::Shl) {
5332 // This is a value scaled by '1 << the shift amt'.
5333 Scale = 1U << CUI->getZExtValue();
5334 Offset = 0;
5335 return I->getOperand(0);
5336 } else if (I->getOpcode() == Instruction::Mul) {
5337 // This value is scaled by 'CUI'.
5338 Scale = CUI->getZExtValue();
5339 Offset = 0;
5340 return I->getOperand(0);
5341 } else if (I->getOpcode() == Instruction::Add) {
5342 // We have X+C. Check to see if we really have (X*C2)+C1,
5343 // where C1 is divisible by C2.
5344 unsigned SubScale;
5345 Value *SubVal =
5346 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5347 Offset += CUI->getZExtValue();
5348 if (SubScale > 1 && (Offset % SubScale == 0)) {
5349 Scale = SubScale;
5350 return SubVal;
5351 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005352 }
5353 }
5354 }
5355 }
5356 }
5357
5358 // Otherwise, we can't look past this.
5359 Scale = 1;
5360 Offset = 0;
5361 return Val;
5362}
5363
5364
Chris Lattner216be912005-10-24 06:03:58 +00005365/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5366/// try to eliminate the cast by moving the type information into the alloc.
5367Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5368 AllocationInst &AI) {
5369 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005370 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005371
Chris Lattnerac87beb2005-10-24 06:22:12 +00005372 // Remove any uses of AI that are dead.
5373 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5374 std::vector<Instruction*> DeadUsers;
5375 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5376 Instruction *User = cast<Instruction>(*UI++);
5377 if (isInstructionTriviallyDead(User)) {
5378 while (UI != E && *UI == User)
5379 ++UI; // If this instruction uses AI more than once, don't break UI.
5380
5381 // Add operands to the worklist.
5382 AddUsesToWorkList(*User);
5383 ++NumDeadInst;
5384 DEBUG(std::cerr << "IC: DCE: " << *User);
5385
5386 User->eraseFromParent();
5387 removeFromWorkList(User);
5388 }
5389 }
5390
Chris Lattner216be912005-10-24 06:03:58 +00005391 // Get the type really allocated and the type casted to.
5392 const Type *AllocElTy = AI.getAllocatedType();
5393 const Type *CastElTy = PTy->getElementType();
5394 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005395
Chris Lattner7d190672006-10-01 19:40:58 +00005396 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5397 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005398 if (CastElTyAlign < AllocElTyAlign) return 0;
5399
Chris Lattner46705b22005-10-24 06:35:18 +00005400 // If the allocation has multiple uses, only promote it if we are strictly
5401 // increasing the alignment of the resultant allocation. If we keep it the
5402 // same, we open the door to infinite loops of various kinds.
5403 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5404
Chris Lattner216be912005-10-24 06:03:58 +00005405 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5406 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005407 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005408
Chris Lattner8270c332005-10-29 03:19:53 +00005409 // See if we can satisfy the modulus by pulling a scale out of the array
5410 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005411 unsigned ArraySizeScale, ArrayOffset;
5412 Value *NumElements = // See if the array size is a decomposable linear expr.
5413 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5414
Chris Lattner8270c332005-10-29 03:19:53 +00005415 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5416 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005417 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5418 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005419
Chris Lattner8270c332005-10-29 03:19:53 +00005420 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5421 Value *Amt = 0;
5422 if (Scale == 1) {
5423 Amt = NumElements;
5424 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005425 // If the allocation size is constant, form a constant mul expression
5426 Amt = ConstantInt::get(Type::UIntTy, Scale);
5427 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5428 Amt = ConstantExpr::getMul(
5429 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5430 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005431 else if (Scale != 1) {
5432 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5433 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005434 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005435 }
5436
Chris Lattner8f663e82005-10-29 04:36:15 +00005437 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005438 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005439 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5440 Amt = InsertNewInstBefore(Tmp, AI);
5441 }
5442
Chris Lattner216be912005-10-24 06:03:58 +00005443 std::string Name = AI.getName(); AI.setName("");
5444 AllocationInst *New;
5445 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005446 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005447 else
Nate Begeman848622f2005-11-05 09:21:28 +00005448 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005449 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005450
5451 // If the allocation has multiple uses, insert a cast and change all things
5452 // that used it to use the new cast. This will also hack on CI, but it will
5453 // die soon.
5454 if (!AI.hasOneUse()) {
5455 AddUsesToWorkList(AI);
5456 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5457 InsertNewInstBefore(NewCast, AI);
5458 AI.replaceAllUsesWith(NewCast);
5459 }
Chris Lattner216be912005-10-24 06:03:58 +00005460 return ReplaceInstUsesWith(CI, New);
5461}
5462
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005463/// CanEvaluateInDifferentType - Return true if we can take the specified value
5464/// and return it without inserting any new casts. This is used by code that
5465/// tries to decide whether promoting or shrinking integer operations to wider
5466/// or smaller types will allow us to eliminate a truncate or extend.
5467static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5468 int &NumCastsRemoved) {
5469 if (isa<Constant>(V)) return true;
5470
5471 Instruction *I = dyn_cast<Instruction>(V);
5472 if (!I || !I->hasOneUse()) return false;
5473
5474 switch (I->getOpcode()) {
5475 case Instruction::And:
5476 case Instruction::Or:
5477 case Instruction::Xor:
5478 // These operators can all arbitrarily be extended or truncated.
5479 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5480 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5481 case Instruction::Cast:
5482 // If this is a cast from the destination type, we can trivially eliminate
5483 // it, and this will remove a cast overall.
5484 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005485 // If the first operand is itself a cast, and is eliminable, do not count
5486 // this as an eliminable cast. We would prefer to eliminate those two
5487 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005488 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005489 return true;
5490
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005491 ++NumCastsRemoved;
5492 return true;
5493 }
5494 // TODO: Can handle more cases here.
5495 break;
5496 }
5497
5498 return false;
5499}
5500
5501/// EvaluateInDifferentType - Given an expression that
5502/// CanEvaluateInDifferentType returns true for, actually insert the code to
5503/// evaluate the expression.
5504Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5505 if (Constant *C = dyn_cast<Constant>(V))
5506 return ConstantExpr::getCast(C, Ty);
5507
5508 // Otherwise, it must be an instruction.
5509 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005510 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005511 switch (I->getOpcode()) {
5512 case Instruction::And:
5513 case Instruction::Or:
5514 case Instruction::Xor: {
5515 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5516 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5517 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5518 LHS, RHS, I->getName());
5519 break;
5520 }
5521 case Instruction::Cast:
5522 // If this is a cast from the destination type, return the input.
5523 if (I->getOperand(0)->getType() == Ty)
5524 return I->getOperand(0);
5525
5526 // TODO: Can handle more cases here.
5527 assert(0 && "Unreachable!");
5528 break;
5529 }
5530
5531 return InsertNewInstBefore(Res, *I);
5532}
5533
Chris Lattner216be912005-10-24 06:03:58 +00005534
Chris Lattner48a44f72002-05-02 17:06:02 +00005535// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005536//
Chris Lattner113f4f42002-06-25 16:13:24 +00005537Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005538 Value *Src = CI.getOperand(0);
5539
Chris Lattner48a44f72002-05-02 17:06:02 +00005540 // If the user is casting a value to the same type, eliminate this cast
5541 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005542 if (CI.getType() == Src->getType())
5543 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005544
Chris Lattner81a7a232004-10-16 18:11:37 +00005545 if (isa<UndefValue>(Src)) // cast undef -> undef
5546 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5547
Chris Lattner48a44f72002-05-02 17:06:02 +00005548 // If casting the result of another cast instruction, try to eliminate this
5549 // one!
5550 //
Chris Lattner86102b82005-01-01 16:22:27 +00005551 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5552 Value *A = CSrc->getOperand(0);
5553 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5554 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005555 // This instruction now refers directly to the cast's src operand. This
5556 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005557 CI.setOperand(0, CSrc->getOperand(0));
5558 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005559 }
5560
Chris Lattner650b6da2002-08-02 20:00:25 +00005561 // If this is an A->B->A cast, and we are dealing with integral types, try
5562 // to convert this into a logical 'and' instruction.
5563 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005564 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005565 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005566 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005567 CSrc->getType()->getPrimitiveSizeInBits() <
5568 CI.getType()->getPrimitiveSizeInBits()&&
5569 A->getType()->getPrimitiveSizeInBits() ==
5570 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005571 assert(CSrc->getType() != Type::ULongTy &&
5572 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005573 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005574 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005575 AndValue);
5576 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5577 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5578 if (And->getType() != CI.getType()) {
5579 And->setName(CSrc->getName()+".mask");
5580 InsertNewInstBefore(And, CI);
5581 And = new CastInst(And, CI.getType());
5582 }
5583 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005584 }
5585 }
Chris Lattner2590e512006-02-07 06:56:34 +00005586
Chris Lattner03841652004-05-25 04:29:21 +00005587 // If this is a cast to bool, turn it into the appropriate setne instruction.
5588 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005589 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005590 Constant::getNullValue(CI.getOperand(0)->getType()));
5591
Chris Lattner2590e512006-02-07 06:56:34 +00005592 // See if we can simplify any instructions used by the LHS whose sole
5593 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005594 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5595 uint64_t KnownZero, KnownOne;
5596 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5597 KnownZero, KnownOne))
5598 return &CI;
5599 }
Chris Lattner2590e512006-02-07 06:56:34 +00005600
Chris Lattnerd0d51602003-06-21 23:12:02 +00005601 // If casting the result of a getelementptr instruction with no offset, turn
5602 // this into a cast of the original pointer!
5603 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005604 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005605 bool AllZeroOperands = true;
5606 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5607 if (!isa<Constant>(GEP->getOperand(i)) ||
5608 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5609 AllZeroOperands = false;
5610 break;
5611 }
5612 if (AllZeroOperands) {
5613 CI.setOperand(0, GEP->getOperand(0));
5614 return &CI;
5615 }
5616 }
5617
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005618 // If we are casting a malloc or alloca to a pointer to a type of the same
5619 // size, rewrite the allocation instruction to allocate the "right" type.
5620 //
5621 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005622 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5623 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005624
Chris Lattner86102b82005-01-01 16:22:27 +00005625 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5626 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5627 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005628 if (isa<PHINode>(Src))
5629 if (Instruction *NV = FoldOpIntoPhi(CI))
5630 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005631
5632 // If the source and destination are pointers, and this cast is equivalent to
5633 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5634 // This can enhance SROA and other transforms that want type-safe pointers.
5635 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5636 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5637 const Type *DstTy = DstPTy->getElementType();
5638 const Type *SrcTy = SrcPTy->getElementType();
5639
5640 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5641 unsigned NumZeros = 0;
5642 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005643 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5644 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005645 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5646 ++NumZeros;
5647 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005648
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005649 // If we found a path from the src to dest, create the getelementptr now.
5650 if (SrcTy == DstTy) {
5651 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5652 return new GetElementPtrInst(Src, Idxs);
5653 }
5654 }
5655
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005656 // If the source value is an instruction with only this use, we can attempt to
5657 // propagate the cast into the instruction. Also, only handle integral types
5658 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005659 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005660 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005661 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005662
5663 int NumCastsRemoved = 0;
5664 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5665 // If this cast is a truncate, evaluting in a different type always
5666 // eliminates the cast, so it is always a win. If this is a noop-cast
5667 // this just removes a noop cast which isn't pointful, but simplifies
5668 // the code. If this is a zero-extension, we need to do an AND to
5669 // maintain the clear top-part of the computation, so we require that
5670 // the input have eliminated at least one cast. If this is a sign
5671 // extension, we insert two new casts (to do the extension) so we
5672 // require that two casts have been eliminated.
5673 bool DoXForm;
5674 switch (getCastType(Src->getType(), CI.getType())) {
5675 default: assert(0 && "Unknown cast type!");
5676 case Noop:
5677 case Truncate:
5678 DoXForm = true;
5679 break;
5680 case Zeroext:
5681 DoXForm = NumCastsRemoved >= 1;
5682 break;
5683 case Signext:
5684 DoXForm = NumCastsRemoved >= 2;
5685 break;
5686 }
5687
5688 if (DoXForm) {
5689 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5690 assert(Res->getType() == CI.getType());
5691 switch (getCastType(Src->getType(), CI.getType())) {
5692 default: assert(0 && "Unknown cast type!");
5693 case Noop:
5694 case Truncate:
5695 // Just replace this cast with the result.
5696 return ReplaceInstUsesWith(CI, Res);
5697 case Zeroext: {
5698 // We need to emit an AND to clear the high bits.
5699 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5700 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5701 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005702 Constant *C =
5703 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005704 C = ConstantExpr::getCast(C, CI.getType());
5705 return BinaryOperator::createAnd(Res, C);
5706 }
5707 case Signext:
5708 // We need to emit a cast to truncate, then a cast to sext.
5709 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5710 CI.getType());
5711 }
5712 }
5713 }
5714
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005715 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005716 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5717 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005718
5719 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5720 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5721
5722 switch (SrcI->getOpcode()) {
5723 case Instruction::Add:
5724 case Instruction::Mul:
5725 case Instruction::And:
5726 case Instruction::Or:
5727 case Instruction::Xor:
5728 // If we are discarding information, or just changing the sign, rewrite.
5729 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5730 // Don't insert two casts if they cannot be eliminated. We allow two
5731 // casts to be inserted if the sizes are the same. This could only be
5732 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005733 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5734 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005735 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5736 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5737 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5738 ->getOpcode(), Op0c, Op1c);
5739 }
5740 }
Chris Lattner72086162005-05-06 02:07:39 +00005741
5742 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5743 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005744 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005745 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5746 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5747 return BinaryOperator::createXor(New,
5748 ConstantInt::get(CI.getType(), 1));
5749 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005750 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005751 case Instruction::SDiv:
5752 case Instruction::UDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +00005753 case Instruction::SRem:
5754 case Instruction::URem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005755 // If we are just changing the sign, rewrite.
5756 if (DestBitSize == SrcBitSize) {
5757 // Don't insert two casts if they cannot be eliminated. We allow two
5758 // casts to be inserted if the sizes are the same. This could only be
5759 // converting signedness, which is a noop.
5760 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5761 !ValueRequiresCast(Op0, DestTy, TD)) {
5762 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5763 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5764 return BinaryOperator::create(
5765 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5766 }
5767 }
5768 break;
5769
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005770 case Instruction::Shl:
5771 // Allow changing the sign of the source operand. Do not allow changing
5772 // the size of the shift, UNLESS the shift amount is a constant. We
Reid Spencerfdff9382006-11-08 06:47:33 +00005773 // must not change variable sized shifts to a smaller size, because it
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005774 // is undefined to shift more bits out than exist in the value.
5775 if (DestBitSize == SrcBitSize ||
5776 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5777 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5778 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5779 }
5780 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00005781 case Instruction::AShr:
Chris Lattner87380412005-05-06 04:18:52 +00005782 // If this is a signed shr, and if all bits shifted in are about to be
5783 // truncated off, turn it into an unsigned shr to allow greater
5784 // simplifications.
Reid Spencerfdff9382006-11-08 06:47:33 +00005785 if (DestBitSize < SrcBitSize &&
Chris Lattner87380412005-05-06 04:18:52 +00005786 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005787 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005788 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005789 // Insert the new logical shift right.
5790 return new ShiftInst(Instruction::LShr, Op0, Op1);
Chris Lattner87380412005-05-06 04:18:52 +00005791 }
5792 }
5793 break;
5794
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005795 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005796 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005797 // We if we are just checking for a seteq of a single bit and casting it
5798 // to an integer. If so, shift the bit to the appropriate place then
5799 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005800 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005801 uint64_t Op1CV = Op1C->getZExtValue();
5802 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5803 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5804 // cast (X == 1) to int --> X iff X has only the low bit set.
5805 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5806 // cast (X != 0) to int --> X iff X has only the low bit set.
5807 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5808 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5809 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5810 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5811 // If Op1C some other power of two, convert:
5812 uint64_t KnownZero, KnownOne;
5813 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5814 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5815
5816 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5817 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5818 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5819 // (X&4) == 2 --> false
5820 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005821 Constant *Res = ConstantBool::get(isSetNE);
5822 Res = ConstantExpr::getCast(Res, CI.getType());
5823 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005824 }
5825
5826 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5827 Value *In = Op0;
5828 if (ShiftAmt) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005829 // Perform a logical shr by shiftamt.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005830 // Insert the shift to put the result in the low bit.
Reid Spencerfdff9382006-11-08 06:47:33 +00005831 In = InsertNewInstBefore(new ShiftInst(Instruction::LShr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005832 ConstantInt::get(Type::UByteTy, ShiftAmt),
5833 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005834 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005835
5836 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5837 Constant *One = ConstantInt::get(In->getType(), 1);
5838 In = BinaryOperator::createXor(In, One, "tmp");
5839 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005840 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005841
5842 if (CI.getType() == In->getType())
5843 return ReplaceInstUsesWith(CI, In);
5844 else
5845 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005846 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005847 }
5848 }
5849 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005850 }
5851 }
Chris Lattner99155be2006-05-25 23:24:33 +00005852
5853 if (SrcI->hasOneUse()) {
5854 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5855 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5856 // because the inputs are known to be a vector. Check to see if this is
5857 // a cast to a vector with the same # elts.
5858 if (isa<PackedType>(CI.getType()) &&
5859 cast<PackedType>(CI.getType())->getNumElements() ==
5860 SVI->getType()->getNumElements()) {
5861 CastInst *Tmp;
5862 // If either of the operands is a cast from CI.getType(), then
5863 // evaluating the shuffle in the casted destination's type will allow
5864 // us to eliminate at least one cast.
5865 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5866 Tmp->getOperand(0)->getType() == CI.getType()) ||
5867 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005868 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005869 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5870 CI.getType(), &CI);
5871 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5872 CI.getType(), &CI);
5873 // Return a new shuffle vector. Use the same element ID's, as we
5874 // know the vector types match #elts.
5875 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5876 }
5877 }
5878 }
5879 }
5880 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005881
Chris Lattner260ab202002-04-18 17:39:14 +00005882 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005883}
5884
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005885/// GetSelectFoldableOperands - We want to turn code that looks like this:
5886/// %C = or %A, %B
5887/// %D = select %cond, %C, %A
5888/// into:
5889/// %C = select %cond, %B, 0
5890/// %D = or %A, %C
5891///
5892/// Assuming that the specified instruction is an operand to the select, return
5893/// a bitmask indicating which operands of this instruction are foldable if they
5894/// equal the other incoming value of the select.
5895///
5896static unsigned GetSelectFoldableOperands(Instruction *I) {
5897 switch (I->getOpcode()) {
5898 case Instruction::Add:
5899 case Instruction::Mul:
5900 case Instruction::And:
5901 case Instruction::Or:
5902 case Instruction::Xor:
5903 return 3; // Can fold through either operand.
5904 case Instruction::Sub: // Can only fold on the amount subtracted.
5905 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00005906 case Instruction::LShr:
5907 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005908 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005909 default:
5910 return 0; // Cannot fold
5911 }
5912}
5913
5914/// GetSelectFoldableConstant - For the same transformation as the previous
5915/// function, return the identity constant that goes into the select.
5916static Constant *GetSelectFoldableConstant(Instruction *I) {
5917 switch (I->getOpcode()) {
5918 default: assert(0 && "This cannot happen!"); abort();
5919 case Instruction::Add:
5920 case Instruction::Sub:
5921 case Instruction::Or:
5922 case Instruction::Xor:
5923 return Constant::getNullValue(I->getType());
5924 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00005925 case Instruction::LShr:
5926 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005927 return Constant::getNullValue(Type::UByteTy);
5928 case Instruction::And:
5929 return ConstantInt::getAllOnesValue(I->getType());
5930 case Instruction::Mul:
5931 return ConstantInt::get(I->getType(), 1);
5932 }
5933}
5934
Chris Lattner411336f2005-01-19 21:50:18 +00005935/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5936/// have the same opcode and only one use each. Try to simplify this.
5937Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5938 Instruction *FI) {
5939 if (TI->getNumOperands() == 1) {
5940 // If this is a non-volatile load or a cast from the same type,
5941 // merge.
5942 if (TI->getOpcode() == Instruction::Cast) {
5943 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5944 return 0;
5945 } else {
5946 return 0; // unknown unary op.
5947 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005948
Chris Lattner411336f2005-01-19 21:50:18 +00005949 // Fold this by inserting a select from the input values.
5950 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5951 FI->getOperand(0), SI.getName()+".v");
5952 InsertNewInstBefore(NewSI, SI);
5953 return new CastInst(NewSI, TI->getType());
5954 }
5955
5956 // Only handle binary operators here.
5957 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5958 return 0;
5959
5960 // Figure out if the operations have any operands in common.
5961 Value *MatchOp, *OtherOpT, *OtherOpF;
5962 bool MatchIsOpZero;
5963 if (TI->getOperand(0) == FI->getOperand(0)) {
5964 MatchOp = TI->getOperand(0);
5965 OtherOpT = TI->getOperand(1);
5966 OtherOpF = FI->getOperand(1);
5967 MatchIsOpZero = true;
5968 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5969 MatchOp = TI->getOperand(1);
5970 OtherOpT = TI->getOperand(0);
5971 OtherOpF = FI->getOperand(0);
5972 MatchIsOpZero = false;
5973 } else if (!TI->isCommutative()) {
5974 return 0;
5975 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5976 MatchOp = TI->getOperand(0);
5977 OtherOpT = TI->getOperand(1);
5978 OtherOpF = FI->getOperand(0);
5979 MatchIsOpZero = true;
5980 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5981 MatchOp = TI->getOperand(1);
5982 OtherOpT = TI->getOperand(0);
5983 OtherOpF = FI->getOperand(1);
5984 MatchIsOpZero = true;
5985 } else {
5986 return 0;
5987 }
5988
5989 // If we reach here, they do have operations in common.
5990 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5991 OtherOpF, SI.getName()+".v");
5992 InsertNewInstBefore(NewSI, SI);
5993
5994 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5995 if (MatchIsOpZero)
5996 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5997 else
5998 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5999 } else {
6000 if (MatchIsOpZero)
6001 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6002 else
6003 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6004 }
6005}
6006
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006007Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006008 Value *CondVal = SI.getCondition();
6009 Value *TrueVal = SI.getTrueValue();
6010 Value *FalseVal = SI.getFalseValue();
6011
6012 // select true, X, Y -> X
6013 // select false, X, Y -> Y
6014 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006015 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006016
6017 // select C, X, X -> X
6018 if (TrueVal == FalseVal)
6019 return ReplaceInstUsesWith(SI, TrueVal);
6020
Chris Lattner81a7a232004-10-16 18:11:37 +00006021 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6022 return ReplaceInstUsesWith(SI, FalseVal);
6023 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6024 return ReplaceInstUsesWith(SI, TrueVal);
6025 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6026 if (isa<Constant>(TrueVal))
6027 return ReplaceInstUsesWith(SI, TrueVal);
6028 else
6029 return ReplaceInstUsesWith(SI, FalseVal);
6030 }
6031
Chris Lattner1c631e82004-04-08 04:43:23 +00006032 if (SI.getType() == Type::BoolTy)
6033 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006034 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006035 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006036 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006037 } else {
6038 // Change: A = select B, false, C --> A = and !B, C
6039 Value *NotCond =
6040 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6041 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006042 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006043 }
6044 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006045 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006046 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006047 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006048 } else {
6049 // Change: A = select B, C, true --> A = or !B, C
6050 Value *NotCond =
6051 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6052 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006053 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006054 }
6055 }
6056
Chris Lattner183b3362004-04-09 19:05:30 +00006057 // Selecting between two integer constants?
6058 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6059 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6060 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006061 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006062 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006063 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006064 // select C, 0, 1 -> cast !C to int
6065 Value *NotCond =
6066 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006067 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006068 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006069 }
Chris Lattner35167c32004-06-09 07:59:58 +00006070
Chris Lattner380c7e92006-09-20 04:44:59 +00006071 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6072
6073 // (x <s 0) ? -1 : 0 -> sra x, 31
6074 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6075 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6076 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6077 bool CanXForm = false;
6078 if (CmpCst->getType()->isSigned())
6079 CanXForm = CmpCst->isNullValue() &&
6080 IC->getOpcode() == Instruction::SetLT;
6081 else {
6082 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006083 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006084 IC->getOpcode() == Instruction::SetGT;
6085 }
6086
6087 if (CanXForm) {
6088 // The comparison constant and the result are not neccessarily the
6089 // same width. In any case, the first step to do is make sure
6090 // that X is signed.
6091 Value *X = IC->getOperand(0);
6092 if (!X->getType()->isSigned())
6093 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6094
6095 // Now that X is signed, we have to make the all ones value. Do
6096 // this by inserting a new SRA.
6097 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006098 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006099 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006100 ShAmt, "ones");
6101 InsertNewInstBefore(SRA, SI);
6102
6103 // Finally, convert to the type of the select RHS. If this is
6104 // smaller than the compare value, it will truncate the ones to
6105 // fit. If it is larger, it will sext the ones to fit.
6106 return new CastInst(SRA, SI.getType());
6107 }
6108 }
6109
6110
6111 // If one of the constants is zero (we know they can't both be) and we
6112 // have a setcc instruction with zero, and we have an 'and' with the
6113 // non-constant value, eliminate this whole mess. This corresponds to
6114 // cases like this: ((X & 27) ? 27 : 0)
6115 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006116 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006117 cast<Constant>(IC->getOperand(1))->isNullValue())
6118 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6119 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006120 isa<ConstantInt>(ICA->getOperand(1)) &&
6121 (ICA->getOperand(1) == TrueValC ||
6122 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006123 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6124 // Okay, now we know that everything is set up, we just don't
6125 // know whether we have a setne or seteq and whether the true or
6126 // false val is the zero.
6127 bool ShouldNotVal = !TrueValC->isNullValue();
6128 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6129 Value *V = ICA;
6130 if (ShouldNotVal)
6131 V = InsertNewInstBefore(BinaryOperator::create(
6132 Instruction::Xor, V, ICA->getOperand(1)), SI);
6133 return ReplaceInstUsesWith(SI, V);
6134 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006135 }
Chris Lattner533bc492004-03-30 19:37:13 +00006136 }
Chris Lattner623fba12004-04-10 22:21:27 +00006137
6138 // See if we are selecting two values based on a comparison of the two values.
6139 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6140 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6141 // Transform (X == Y) ? X : Y -> Y
6142 if (SCI->getOpcode() == Instruction::SetEQ)
6143 return ReplaceInstUsesWith(SI, FalseVal);
6144 // Transform (X != Y) ? X : Y -> X
6145 if (SCI->getOpcode() == Instruction::SetNE)
6146 return ReplaceInstUsesWith(SI, TrueVal);
6147 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6148
6149 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6150 // Transform (X == Y) ? Y : X -> X
6151 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006152 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006153 // Transform (X != Y) ? Y : X -> Y
6154 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006155 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006156 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6157 }
6158 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006159
Chris Lattnera04c9042005-01-13 22:52:24 +00006160 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6161 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6162 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006163 Instruction *AddOp = 0, *SubOp = 0;
6164
Chris Lattner411336f2005-01-19 21:50:18 +00006165 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6166 if (TI->getOpcode() == FI->getOpcode())
6167 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6168 return IV;
6169
6170 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6171 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006172 if (TI->getOpcode() == Instruction::Sub &&
6173 FI->getOpcode() == Instruction::Add) {
6174 AddOp = FI; SubOp = TI;
6175 } else if (FI->getOpcode() == Instruction::Sub &&
6176 TI->getOpcode() == Instruction::Add) {
6177 AddOp = TI; SubOp = FI;
6178 }
6179
6180 if (AddOp) {
6181 Value *OtherAddOp = 0;
6182 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6183 OtherAddOp = AddOp->getOperand(1);
6184 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6185 OtherAddOp = AddOp->getOperand(0);
6186 }
6187
6188 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006189 // So at this point we know we have (Y -> OtherAddOp):
6190 // select C, (add X, Y), (sub X, Z)
6191 Value *NegVal; // Compute -Z
6192 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6193 NegVal = ConstantExpr::getNeg(C);
6194 } else {
6195 NegVal = InsertNewInstBefore(
6196 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006197 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006198
6199 Value *NewTrueOp = OtherAddOp;
6200 Value *NewFalseOp = NegVal;
6201 if (AddOp != TI)
6202 std::swap(NewTrueOp, NewFalseOp);
6203 Instruction *NewSel =
6204 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6205
6206 NewSel = InsertNewInstBefore(NewSel, SI);
6207 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006208 }
6209 }
6210 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006211
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006212 // See if we can fold the select into one of our operands.
6213 if (SI.getType()->isInteger()) {
6214 // See the comment above GetSelectFoldableOperands for a description of the
6215 // transformation we are doing here.
6216 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6217 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6218 !isa<Constant>(FalseVal))
6219 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6220 unsigned OpToFold = 0;
6221 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6222 OpToFold = 1;
6223 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6224 OpToFold = 2;
6225 }
6226
6227 if (OpToFold) {
6228 Constant *C = GetSelectFoldableConstant(TVI);
6229 std::string Name = TVI->getName(); TVI->setName("");
6230 Instruction *NewSel =
6231 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6232 Name);
6233 InsertNewInstBefore(NewSel, SI);
6234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6235 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6236 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6237 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6238 else {
6239 assert(0 && "Unknown instruction!!");
6240 }
6241 }
6242 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006243
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006244 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6245 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6246 !isa<Constant>(TrueVal))
6247 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6248 unsigned OpToFold = 0;
6249 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6250 OpToFold = 1;
6251 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6252 OpToFold = 2;
6253 }
6254
6255 if (OpToFold) {
6256 Constant *C = GetSelectFoldableConstant(FVI);
6257 std::string Name = FVI->getName(); FVI->setName("");
6258 Instruction *NewSel =
6259 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6260 Name);
6261 InsertNewInstBefore(NewSel, SI);
6262 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6263 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6264 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6265 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6266 else {
6267 assert(0 && "Unknown instruction!!");
6268 }
6269 }
6270 }
6271 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006272
6273 if (BinaryOperator::isNot(CondVal)) {
6274 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6275 SI.setOperand(1, FalseVal);
6276 SI.setOperand(2, TrueVal);
6277 return &SI;
6278 }
6279
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006280 return 0;
6281}
6282
Chris Lattner82f2ef22006-03-06 20:18:44 +00006283/// GetKnownAlignment - If the specified pointer has an alignment that we can
6284/// determine, return it, otherwise return 0.
6285static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6286 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6287 unsigned Align = GV->getAlignment();
6288 if (Align == 0 && TD)
6289 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6290 return Align;
6291 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6292 unsigned Align = AI->getAlignment();
6293 if (Align == 0 && TD) {
6294 if (isa<AllocaInst>(AI))
6295 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6296 else if (isa<MallocInst>(AI)) {
6297 // Malloc returns maximally aligned memory.
6298 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6299 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6300 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6301 }
6302 }
6303 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006304 } else if (isa<CastInst>(V) ||
6305 (isa<ConstantExpr>(V) &&
6306 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6307 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006308 if (isa<PointerType>(CI->getOperand(0)->getType()))
6309 return GetKnownAlignment(CI->getOperand(0), TD);
6310 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006311 } else if (isa<GetElementPtrInst>(V) ||
6312 (isa<ConstantExpr>(V) &&
6313 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6314 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006315 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6316 if (BaseAlignment == 0) return 0;
6317
6318 // If all indexes are zero, it is just the alignment of the base pointer.
6319 bool AllZeroOperands = true;
6320 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6321 if (!isa<Constant>(GEPI->getOperand(i)) ||
6322 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6323 AllZeroOperands = false;
6324 break;
6325 }
6326 if (AllZeroOperands)
6327 return BaseAlignment;
6328
6329 // Otherwise, if the base alignment is >= the alignment we expect for the
6330 // base pointer type, then we know that the resultant pointer is aligned at
6331 // least as much as its type requires.
6332 if (!TD) return 0;
6333
6334 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6335 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006336 <= BaseAlignment) {
6337 const Type *GEPTy = GEPI->getType();
6338 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6339 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006340 return 0;
6341 }
6342 return 0;
6343}
6344
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006345
Chris Lattnerc66b2232006-01-13 20:11:04 +00006346/// visitCallInst - CallInst simplification. This mostly only handles folding
6347/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6348/// the heavy lifting.
6349///
Chris Lattner970c33a2003-06-19 17:00:31 +00006350Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006351 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6352 if (!II) return visitCallSite(&CI);
6353
Chris Lattner51ea1272004-02-28 05:22:00 +00006354 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6355 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006356 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006357 bool Changed = false;
6358
6359 // memmove/cpy/set of zero bytes is a noop.
6360 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6361 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6362
Chris Lattner00648e12004-10-12 04:52:52 +00006363 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006364 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006365 // Replace the instruction with just byte operations. We would
6366 // transform other cases to loads/stores, but we don't know if
6367 // alignment is sufficient.
6368 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006369 }
6370
Chris Lattner00648e12004-10-12 04:52:52 +00006371 // If we have a memmove and the source operation is a constant global,
6372 // then the source and dest pointers can't alias, so we can change this
6373 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006374 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006375 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6376 if (GVSrc->isConstant()) {
6377 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006378 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006379 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006380 Type::UIntTy)
6381 Name = "llvm.memcpy.i32";
6382 else
6383 Name = "llvm.memcpy.i64";
6384 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006385 CI.getCalledFunction()->getFunctionType());
6386 CI.setOperand(0, MemCpy);
6387 Changed = true;
6388 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006389 }
Chris Lattner00648e12004-10-12 04:52:52 +00006390
Chris Lattner82f2ef22006-03-06 20:18:44 +00006391 // If we can determine a pointer alignment that is bigger than currently
6392 // set, update the alignment.
6393 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6394 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6395 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6396 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006397 if (MI->getAlignment()->getZExtValue() < Align) {
6398 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006399 Changed = true;
6400 }
6401 } else if (isa<MemSetInst>(MI)) {
6402 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006403 if (MI->getAlignment()->getZExtValue() < Alignment) {
6404 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006405 Changed = true;
6406 }
6407 }
6408
Chris Lattnerc66b2232006-01-13 20:11:04 +00006409 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006410 } else {
6411 switch (II->getIntrinsicID()) {
6412 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006413 case Intrinsic::ppc_altivec_lvx:
6414 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006415 case Intrinsic::x86_sse_loadu_ps:
6416 case Intrinsic::x86_sse2_loadu_pd:
6417 case Intrinsic::x86_sse2_loadu_dq:
6418 // Turn PPC lvx -> load if the pointer is known aligned.
6419 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006420 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006421 Value *Ptr = InsertCastBefore(II->getOperand(1),
6422 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006423 return new LoadInst(Ptr);
6424 }
6425 break;
6426 case Intrinsic::ppc_altivec_stvx:
6427 case Intrinsic::ppc_altivec_stvxl:
6428 // Turn stvx -> store if the pointer is known aligned.
6429 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006430 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6431 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006432 return new StoreInst(II->getOperand(1), Ptr);
6433 }
6434 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006435 case Intrinsic::x86_sse_storeu_ps:
6436 case Intrinsic::x86_sse2_storeu_pd:
6437 case Intrinsic::x86_sse2_storeu_dq:
6438 case Intrinsic::x86_sse2_storel_dq:
6439 // Turn X86 storeu -> store if the pointer is known aligned.
6440 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6441 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6442 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6443 return new StoreInst(II->getOperand(2), Ptr);
6444 }
6445 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006446
6447 case Intrinsic::x86_sse_cvttss2si: {
6448 // These intrinsics only demands the 0th element of its input vector. If
6449 // we can simplify the input based on that, do so now.
6450 uint64_t UndefElts;
6451 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6452 UndefElts)) {
6453 II->setOperand(1, V);
6454 return II;
6455 }
6456 break;
6457 }
6458
Chris Lattnere79d2492006-04-06 19:19:17 +00006459 case Intrinsic::ppc_altivec_vperm:
6460 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6461 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6462 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6463
6464 // Check that all of the elements are integer constants or undefs.
6465 bool AllEltsOk = true;
6466 for (unsigned i = 0; i != 16; ++i) {
6467 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6468 !isa<UndefValue>(Mask->getOperand(i))) {
6469 AllEltsOk = false;
6470 break;
6471 }
6472 }
6473
6474 if (AllEltsOk) {
6475 // Cast the input vectors to byte vectors.
6476 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6477 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6478 Value *Result = UndefValue::get(Op0->getType());
6479
6480 // Only extract each element once.
6481 Value *ExtractedElts[32];
6482 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6483
6484 for (unsigned i = 0; i != 16; ++i) {
6485 if (isa<UndefValue>(Mask->getOperand(i)))
6486 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006487 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006488 Idx &= 31; // Match the hardware behavior.
6489
6490 if (ExtractedElts[Idx] == 0) {
6491 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006492 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006493 InsertNewInstBefore(Elt, CI);
6494 ExtractedElts[Idx] = Elt;
6495 }
6496
6497 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006498 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006499 InsertNewInstBefore(cast<Instruction>(Result), CI);
6500 }
6501 return new CastInst(Result, CI.getType());
6502 }
6503 }
6504 break;
6505
Chris Lattner503221f2006-01-13 21:28:09 +00006506 case Intrinsic::stackrestore: {
6507 // If the save is right next to the restore, remove the restore. This can
6508 // happen when variable allocas are DCE'd.
6509 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6510 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6511 BasicBlock::iterator BI = SS;
6512 if (&*++BI == II)
6513 return EraseInstFromFunction(CI);
6514 }
6515 }
6516
6517 // If the stack restore is in a return/unwind block and if there are no
6518 // allocas or calls between the restore and the return, nuke the restore.
6519 TerminatorInst *TI = II->getParent()->getTerminator();
6520 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6521 BasicBlock::iterator BI = II;
6522 bool CannotRemove = false;
6523 for (++BI; &*BI != TI; ++BI) {
6524 if (isa<AllocaInst>(BI) ||
6525 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6526 CannotRemove = true;
6527 break;
6528 }
6529 }
6530 if (!CannotRemove)
6531 return EraseInstFromFunction(CI);
6532 }
6533 break;
6534 }
6535 }
Chris Lattner00648e12004-10-12 04:52:52 +00006536 }
6537
Chris Lattnerc66b2232006-01-13 20:11:04 +00006538 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006539}
6540
6541// InvokeInst simplification
6542//
6543Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006544 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006545}
6546
Chris Lattneraec3d942003-10-07 22:32:43 +00006547// visitCallSite - Improvements for call and invoke instructions.
6548//
6549Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006550 bool Changed = false;
6551
6552 // If the callee is a constexpr cast of a function, attempt to move the cast
6553 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006554 if (transformConstExprCastCall(CS)) return 0;
6555
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006556 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006557
Chris Lattner61d9d812005-05-13 07:09:09 +00006558 if (Function *CalleeF = dyn_cast<Function>(Callee))
6559 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6560 Instruction *OldCall = CS.getInstruction();
6561 // If the call and callee calling conventions don't match, this call must
6562 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006563 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006564 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6565 if (!OldCall->use_empty())
6566 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6567 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6568 return EraseInstFromFunction(*OldCall);
6569 return 0;
6570 }
6571
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006572 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6573 // This instruction is not reachable, just remove it. We insert a store to
6574 // undef so that we know that this code is not reachable, despite the fact
6575 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006576 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006577 UndefValue::get(PointerType::get(Type::BoolTy)),
6578 CS.getInstruction());
6579
6580 if (!CS.getInstruction()->use_empty())
6581 CS.getInstruction()->
6582 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6583
6584 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6585 // Don't break the CFG, insert a dummy cond branch.
6586 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006587 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006588 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006589 return EraseInstFromFunction(*CS.getInstruction());
6590 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006591
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006592 const PointerType *PTy = cast<PointerType>(Callee->getType());
6593 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6594 if (FTy->isVarArg()) {
6595 // See if we can optimize any arguments passed through the varargs area of
6596 // the call.
6597 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6598 E = CS.arg_end(); I != E; ++I)
6599 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6600 // If this cast does not effect the value passed through the varargs
6601 // area, we can eliminate the use of the cast.
6602 Value *Op = CI->getOperand(0);
6603 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6604 *I = Op;
6605 Changed = true;
6606 }
6607 }
6608 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006609
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006610 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006611}
6612
Chris Lattner970c33a2003-06-19 17:00:31 +00006613// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6614// attempt to move the cast to the arguments of the call/invoke.
6615//
6616bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6617 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6618 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006619 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006620 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006621 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006622 Instruction *Caller = CS.getInstruction();
6623
6624 // Okay, this is a cast from a function to a different type. Unless doing so
6625 // would cause a type conversion of one of our arguments, change this call to
6626 // be a direct call with arguments casted to the appropriate types.
6627 //
6628 const FunctionType *FT = Callee->getFunctionType();
6629 const Type *OldRetTy = Caller->getType();
6630
Chris Lattner1f7942f2004-01-14 06:06:08 +00006631 // Check to see if we are changing the return type...
6632 if (OldRetTy != FT->getReturnType()) {
6633 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006634 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6635 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006636 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006637 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006638 return false; // Cannot transform this return value...
6639
6640 // If the callsite is an invoke instruction, and the return value is used by
6641 // a PHI node in a successor, we cannot change the return type of the call
6642 // because there is no place to put the cast instruction (without breaking
6643 // the critical edge). Bail out in this case.
6644 if (!Caller->use_empty())
6645 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6646 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6647 UI != E; ++UI)
6648 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6649 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006650 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006651 return false;
6652 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006653
6654 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6655 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006656
Chris Lattner970c33a2003-06-19 17:00:31 +00006657 CallSite::arg_iterator AI = CS.arg_begin();
6658 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6659 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006660 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006661 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006662 //Either we can cast directly, or we can upconvert the argument
6663 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6664 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6665 ParamTy->isSigned() == ActTy->isSigned() &&
6666 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6667 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006668 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006669 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006670 }
6671
6672 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6673 Callee->isExternal())
6674 return false; // Do not delete arguments unless we have a function body...
6675
6676 // Okay, we decided that this is a safe thing to do: go ahead and start
6677 // inserting cast instructions as necessary...
6678 std::vector<Value*> Args;
6679 Args.reserve(NumActualArgs);
6680
6681 AI = CS.arg_begin();
6682 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6683 const Type *ParamTy = FT->getParamType(i);
6684 if ((*AI)->getType() == ParamTy) {
6685 Args.push_back(*AI);
6686 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006687 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6688 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006689 }
6690 }
6691
6692 // If the function takes more arguments than the call was taking, add them
6693 // now...
6694 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6695 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6696
6697 // If we are removing arguments to the function, emit an obnoxious warning...
6698 if (FT->getNumParams() < NumActualArgs)
6699 if (!FT->isVarArg()) {
6700 std::cerr << "WARNING: While resolving call to function '"
6701 << Callee->getName() << "' arguments were dropped!\n";
6702 } else {
6703 // Add all of the arguments in their promoted form to the arg list...
6704 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6705 const Type *PTy = getPromotedType((*AI)->getType());
6706 if (PTy != (*AI)->getType()) {
6707 // Must promote to pass through va_arg area!
6708 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6709 InsertNewInstBefore(Cast, *Caller);
6710 Args.push_back(Cast);
6711 } else {
6712 Args.push_back(*AI);
6713 }
6714 }
6715 }
6716
6717 if (FT->getReturnType() == Type::VoidTy)
6718 Caller->setName(""); // Void type should not have a name...
6719
6720 Instruction *NC;
6721 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006722 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006723 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006724 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006725 } else {
6726 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006727 if (cast<CallInst>(Caller)->isTailCall())
6728 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006729 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006730 }
6731
6732 // Insert a cast of the return type as necessary...
6733 Value *NV = NC;
6734 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6735 if (NV->getType() != Type::VoidTy) {
6736 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006737
6738 // If this is an invoke instruction, we should insert it after the first
6739 // non-phi, instruction in the normal successor block.
6740 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6741 BasicBlock::iterator I = II->getNormalDest()->begin();
6742 while (isa<PHINode>(I)) ++I;
6743 InsertNewInstBefore(NC, *I);
6744 } else {
6745 // Otherwise, it's a call, just insert cast right after the call instr
6746 InsertNewInstBefore(NC, *Caller);
6747 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006748 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006749 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006750 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006751 }
6752 }
6753
6754 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6755 Caller->replaceAllUsesWith(NV);
6756 Caller->getParent()->getInstList().erase(Caller);
6757 removeFromWorkList(Caller);
6758 return true;
6759}
6760
Chris Lattnercadac0c2006-11-01 04:51:18 +00006761/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6762/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6763/// and a single binop.
6764Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6765 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006766 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6767 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006768 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00006769 Value *LHSVal = FirstInst->getOperand(0);
6770 Value *RHSVal = FirstInst->getOperand(1);
6771
6772 const Type *LHSType = LHSVal->getType();
6773 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00006774
6775 // Scan to see if all operands are the same opcode, all have one use, and all
6776 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006777 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006778 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006779 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6780 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00006781 // types or GEP's with different index types.
6782 I->getOperand(0)->getType() != LHSType ||
6783 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00006784 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00006785
6786 // Keep track of which operand needs a phi node.
6787 if (I->getOperand(0) != LHSVal) LHSVal = 0;
6788 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00006789 }
6790
Chris Lattnercd62f112006-11-08 19:29:23 +00006791 // Otherwise, this is safe and profitable to transform. Create up to two phi
6792 // nodes.
6793 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00006794 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00006795 Value *InRHS = FirstInst->getOperand(1);
Chris Lattnercadac0c2006-11-01 04:51:18 +00006796
Chris Lattnercd62f112006-11-08 19:29:23 +00006797 if (LHSVal == 0) {
6798 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
6799 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6800 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006801 InsertNewInstBefore(NewLHS, PN);
6802 LHSVal = NewLHS;
6803 }
Chris Lattnercd62f112006-11-08 19:29:23 +00006804
6805 if (RHSVal == 0) {
6806 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
6807 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6808 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006809 InsertNewInstBefore(NewRHS, PN);
6810 RHSVal = NewRHS;
6811 }
6812
Chris Lattnercd62f112006-11-08 19:29:23 +00006813 // Add all operands to the new PHIs.
6814 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6815 if (NewLHS) {
6816 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6817 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6818 }
6819 if (NewRHS) {
6820 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6821 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6822 }
6823 }
6824
Chris Lattnercadac0c2006-11-01 04:51:18 +00006825 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00006826 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
6827 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
6828 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
6829 else {
6830 assert(isa<GetElementPtrInst>(FirstInst));
6831 return new GetElementPtrInst(LHSVal, RHSVal);
6832 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00006833}
6834
Chris Lattner14f82c72006-11-01 07:13:54 +00006835/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6836/// of the block that defines it. This means that it must be obvious the value
6837/// of the load is not changed from the point of the load to the end of the
6838/// block it is in.
6839static bool isSafeToSinkLoad(LoadInst *L) {
6840 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6841
6842 for (++BBI; BBI != E; ++BBI)
6843 if (BBI->mayWriteToMemory())
6844 return false;
6845 return true;
6846}
6847
Chris Lattner970c33a2003-06-19 17:00:31 +00006848
Chris Lattner7515cab2004-11-14 19:13:23 +00006849// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6850// operator and they all are only used by the PHI, PHI together their
6851// inputs, and do the operation once, to the result of the PHI.
6852Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6853 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6854
6855 // Scan the instruction, looking for input operations that can be folded away.
6856 // If all input operands to the phi are the same instruction (e.g. a cast from
6857 // the same type or "+42") we can pull the operation through the PHI, reducing
6858 // code size and simplifying code.
6859 Constant *ConstantOp = 0;
6860 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00006861 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00006862 if (isa<CastInst>(FirstInst)) {
6863 CastSrcTy = FirstInst->getOperand(0)->getType();
6864 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006865 // Can fold binop or shift here if the RHS is a constant, otherwise call
6866 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00006867 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006868 if (ConstantOp == 0)
6869 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00006870 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
6871 isVolatile = LI->isVolatile();
6872 // We can't sink the load if the loaded value could be modified between the
6873 // load and the PHI.
6874 if (LI->getParent() != PN.getIncomingBlock(0) ||
6875 !isSafeToSinkLoad(LI))
6876 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00006877 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattnera3acfca2006-11-08 18:49:31 +00006878 if (0 && FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00006879 return FoldPHIArgBinOpIntoPHI(PN);
6880 // Can't handle general GEPs yet.
6881 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006882 } else {
6883 return 0; // Cannot fold this operation.
6884 }
6885
6886 // Check to see if all arguments are the same operation.
6887 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6888 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6889 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6890 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6891 return 0;
6892 if (CastSrcTy) {
6893 if (I->getOperand(0)->getType() != CastSrcTy)
6894 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00006895 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6896 // We can't sink the load if the loaded value could be modified between the
6897 // load and the PHI.
6898 if (LI->isVolatile() != isVolatile ||
6899 LI->getParent() != PN.getIncomingBlock(i) ||
6900 !isSafeToSinkLoad(LI))
6901 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006902 } else if (I->getOperand(1) != ConstantOp) {
6903 return 0;
6904 }
6905 }
6906
6907 // Okay, they are all the same operation. Create a new PHI node of the
6908 // correct type, and PHI together all of the LHS's of the instructions.
6909 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6910 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006911 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006912
6913 Value *InVal = FirstInst->getOperand(0);
6914 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006915
6916 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006917 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6918 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6919 if (NewInVal != InVal)
6920 InVal = 0;
6921 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6922 }
6923
6924 Value *PhiVal;
6925 if (InVal) {
6926 // The new PHI unions all of the same values together. This is really
6927 // common, so we handle it intelligently here for compile-time speed.
6928 PhiVal = InVal;
6929 delete NewPN;
6930 } else {
6931 InsertNewInstBefore(NewPN, PN);
6932 PhiVal = NewPN;
6933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006934
Chris Lattner7515cab2004-11-14 19:13:23 +00006935 // Insert and return the new operation.
6936 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006937 return new CastInst(PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00006938 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00006939 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00006940 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006941 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006942 else
6943 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006944 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006945}
Chris Lattner48a44f72002-05-02 17:06:02 +00006946
Chris Lattner71536432005-01-17 05:10:15 +00006947/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6948/// that is dead.
6949static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6950 if (PN->use_empty()) return true;
6951 if (!PN->hasOneUse()) return false;
6952
6953 // Remember this node, and if we find the cycle, return.
6954 if (!PotentiallyDeadPHIs.insert(PN).second)
6955 return true;
6956
6957 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6958 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006959
Chris Lattner71536432005-01-17 05:10:15 +00006960 return false;
6961}
6962
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006963// PHINode simplification
6964//
Chris Lattner113f4f42002-06-25 16:13:24 +00006965Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006966 // If LCSSA is around, don't mess with Phi nodes
6967 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006968
Owen Andersonae8aa642006-07-10 22:03:18 +00006969 if (Value *V = PN.hasConstantValue())
6970 return ReplaceInstUsesWith(PN, V);
6971
6972 // If the only user of this instruction is a cast instruction, and all of the
6973 // incoming values are constants, change this PHI to merge together the casted
6974 // constants.
6975 if (PN.hasOneUse())
6976 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6977 if (CI->getType() != PN.getType()) { // noop casts will be folded
6978 bool AllConstant = true;
6979 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6980 if (!isa<Constant>(PN.getIncomingValue(i))) {
6981 AllConstant = false;
6982 break;
6983 }
6984 if (AllConstant) {
6985 // Make a new PHI with all casted values.
6986 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6987 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6988 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6989 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6990 PN.getIncomingBlock(i));
6991 }
6992
6993 // Update the cast instruction.
6994 CI->setOperand(0, New);
6995 WorkList.push_back(CI); // revisit the cast instruction to fold.
6996 WorkList.push_back(New); // Make sure to revisit the new Phi
6997 return &PN; // PN is now dead!
6998 }
6999 }
7000
7001 // If all PHI operands are the same operation, pull them through the PHI,
7002 // reducing code size.
7003 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7004 PN.getIncomingValue(0)->hasOneUse())
7005 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7006 return Result;
7007
7008 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7009 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7010 // PHI)... break the cycle.
7011 if (PN.hasOneUse())
7012 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7013 std::set<PHINode*> PotentiallyDeadPHIs;
7014 PotentiallyDeadPHIs.insert(&PN);
7015 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7016 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7017 }
7018
Chris Lattner91daeb52003-12-19 05:58:40 +00007019 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007020}
7021
Chris Lattner69193f92004-04-05 01:30:19 +00007022static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7023 Instruction *InsertPoint,
7024 InstCombiner *IC) {
7025 unsigned PS = IC->getTargetData().getPointerSize();
7026 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00007027 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7028 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00007029 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7030 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007031}
7032
Chris Lattner48a44f72002-05-02 17:06:02 +00007033
Chris Lattner113f4f42002-06-25 16:13:24 +00007034Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007035 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007036 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007037 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007038 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007039 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007040
Chris Lattner81a7a232004-10-16 18:11:37 +00007041 if (isa<UndefValue>(GEP.getOperand(0)))
7042 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7043
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007044 bool HasZeroPointerIndex = false;
7045 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7046 HasZeroPointerIndex = C->isNullValue();
7047
7048 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007049 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007050
Chris Lattner69193f92004-04-05 01:30:19 +00007051 // Eliminate unneeded casts for indices.
7052 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007053 gep_type_iterator GTI = gep_type_begin(GEP);
7054 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7055 if (isa<SequentialType>(*GTI)) {
7056 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7057 Value *Src = CI->getOperand(0);
7058 const Type *SrcTy = Src->getType();
7059 const Type *DestTy = CI->getType();
7060 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007061 if (SrcTy->getPrimitiveSizeInBits() ==
7062 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007063 // We can always eliminate a cast from ulong or long to the other.
7064 // We can always eliminate a cast from uint to int or the other on
7065 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007066 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007067 MadeChange = true;
7068 GEP.setOperand(i, Src);
7069 }
7070 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7071 SrcTy->getPrimitiveSize() == 4) {
7072 // We can always eliminate a cast from int to [u]long. We can
7073 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7074 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007075 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007076 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007077 MadeChange = true;
7078 GEP.setOperand(i, Src);
7079 }
Chris Lattner69193f92004-04-05 01:30:19 +00007080 }
7081 }
7082 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007083 // If we are using a wider index than needed for this platform, shrink it
7084 // to what we need. If the incoming value needs a cast instruction,
7085 // insert it. This explicit cast can make subsequent optimizations more
7086 // obvious.
7087 Value *Op = GEP.getOperand(i);
7088 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007089 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007090 GEP.setOperand(i, ConstantExpr::getCast(C,
7091 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007092 MadeChange = true;
7093 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007094 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007095 GEP.setOperand(i, Op);
7096 MadeChange = true;
7097 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007098
7099 // If this is a constant idx, make sure to canonicalize it to be a signed
7100 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007101 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7102 if (CUI->getType()->isUnsigned()) {
7103 GEP.setOperand(i,
7104 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7105 MadeChange = true;
7106 }
Chris Lattner69193f92004-04-05 01:30:19 +00007107 }
7108 if (MadeChange) return &GEP;
7109
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007110 // Combine Indices - If the source pointer to this getelementptr instruction
7111 // is a getelementptr instruction, combine the indices of the two
7112 // getelementptr instructions into a single instruction.
7113 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007114 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007115 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007116 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007117
7118 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007119 // Note that if our source is a gep chain itself that we wait for that
7120 // chain to be resolved before we perform this transformation. This
7121 // avoids us creating a TON of code in some cases.
7122 //
7123 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7124 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7125 return 0; // Wait until our source is folded to completion.
7126
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007127 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007128
7129 // Find out whether the last index in the source GEP is a sequential idx.
7130 bool EndsWithSequential = false;
7131 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7132 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007133 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007134
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007135 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007136 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007137 // Replace: gep (gep %P, long B), long A, ...
7138 // With: T = long A+B; gep %P, T, ...
7139 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007140 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007141 if (SO1 == Constant::getNullValue(SO1->getType())) {
7142 Sum = GO1;
7143 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7144 Sum = SO1;
7145 } else {
7146 // If they aren't the same type, convert both to an integer of the
7147 // target's pointer size.
7148 if (SO1->getType() != GO1->getType()) {
7149 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7150 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7151 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7152 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7153 } else {
7154 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007155 if (SO1->getType()->getPrimitiveSize() == PS) {
7156 // Convert GO1 to SO1's type.
7157 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7158
7159 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7160 // Convert SO1 to GO1's type.
7161 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7162 } else {
7163 const Type *PT = TD->getIntPtrType();
7164 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7165 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7166 }
7167 }
7168 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007169 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7170 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7171 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007172 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7173 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007174 }
Chris Lattner69193f92004-04-05 01:30:19 +00007175 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007176
7177 // Recycle the GEP we already have if possible.
7178 if (SrcGEPOperands.size() == 2) {
7179 GEP.setOperand(0, SrcGEPOperands[0]);
7180 GEP.setOperand(1, Sum);
7181 return &GEP;
7182 } else {
7183 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7184 SrcGEPOperands.end()-1);
7185 Indices.push_back(Sum);
7186 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7187 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007188 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007189 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007190 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007191 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007192 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7193 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007194 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7195 }
7196
7197 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007198 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007199
Chris Lattner5f667a62004-05-07 22:09:22 +00007200 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007201 // GEP of global variable. If all of the indices for this GEP are
7202 // constants, we can promote this to a constexpr instead of an instruction.
7203
7204 // Scan for nonconstants...
7205 std::vector<Constant*> Indices;
7206 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7207 for (; I != E && isa<Constant>(*I); ++I)
7208 Indices.push_back(cast<Constant>(*I));
7209
7210 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007211 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007212
7213 // Replace all uses of the GEP with the new constexpr...
7214 return ReplaceInstUsesWith(GEP, CE);
7215 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007216 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7217 if (!isa<PointerType>(X->getType())) {
7218 // Not interesting. Source pointer must be a cast from pointer.
7219 } else if (HasZeroPointerIndex) {
7220 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7221 // into : GEP [10 x ubyte]* X, long 0, ...
7222 //
7223 // This occurs when the program declares an array extern like "int X[];"
7224 //
7225 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7226 const PointerType *XTy = cast<PointerType>(X->getType());
7227 if (const ArrayType *XATy =
7228 dyn_cast<ArrayType>(XTy->getElementType()))
7229 if (const ArrayType *CATy =
7230 dyn_cast<ArrayType>(CPTy->getElementType()))
7231 if (CATy->getElementType() == XATy->getElementType()) {
7232 // At this point, we know that the cast source type is a pointer
7233 // to an array of the same type as the destination pointer
7234 // array. Because the array type is never stepped over (there
7235 // is a leading zero) we can fold the cast into this GEP.
7236 GEP.setOperand(0, X);
7237 return &GEP;
7238 }
7239 } else if (GEP.getNumOperands() == 2) {
7240 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007241 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7242 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007243 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7244 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7245 if (isa<ArrayType>(SrcElTy) &&
7246 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7247 TD->getTypeSize(ResElTy)) {
7248 Value *V = InsertNewInstBefore(
7249 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7250 GEP.getOperand(1), GEP.getName()), GEP);
7251 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007252 }
Chris Lattner2a893292005-09-13 18:36:04 +00007253
7254 // Transform things like:
7255 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7256 // (where tmp = 8*tmp2) into:
7257 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7258
7259 if (isa<ArrayType>(SrcElTy) &&
7260 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7261 uint64_t ArrayEltSize =
7262 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7263
7264 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7265 // allow either a mul, shift, or constant here.
7266 Value *NewIdx = 0;
7267 ConstantInt *Scale = 0;
7268 if (ArrayEltSize == 1) {
7269 NewIdx = GEP.getOperand(1);
7270 Scale = ConstantInt::get(NewIdx->getType(), 1);
7271 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007272 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007273 Scale = CI;
7274 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7275 if (Inst->getOpcode() == Instruction::Shl &&
7276 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007277 unsigned ShAmt =
7278 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007279 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007280 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007281 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007282 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007283 NewIdx = Inst->getOperand(0);
7284 } else if (Inst->getOpcode() == Instruction::Mul &&
7285 isa<ConstantInt>(Inst->getOperand(1))) {
7286 Scale = cast<ConstantInt>(Inst->getOperand(1));
7287 NewIdx = Inst->getOperand(0);
7288 }
7289 }
7290
7291 // If the index will be to exactly the right offset with the scale taken
7292 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007293 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007294 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007295 Scale = ConstantInt::get(Scale->getType(),
7296 Scale->getZExtValue() / ArrayEltSize);
7297 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007298 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7299 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7300 NewIdx = InsertNewInstBefore(Sc, GEP);
7301 }
7302
7303 // Insert the new GEP instruction.
7304 Instruction *Idx =
7305 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7306 NewIdx, GEP.getName());
7307 Idx = InsertNewInstBefore(Idx, GEP);
7308 return new CastInst(Idx, GEP.getType());
7309 }
7310 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007311 }
Chris Lattnerca081252001-12-14 16:52:21 +00007312 }
7313
Chris Lattnerca081252001-12-14 16:52:21 +00007314 return 0;
7315}
7316
Chris Lattner1085bdf2002-11-04 16:18:53 +00007317Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7318 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7319 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007320 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7321 const Type *NewTy =
7322 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007323 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007324
7325 // Create and insert the replacement instruction...
7326 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007327 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007328 else {
7329 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007330 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007331 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007332
7333 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007334
Chris Lattner1085bdf2002-11-04 16:18:53 +00007335 // Scan to the end of the allocation instructions, to skip over a block of
7336 // allocas if possible...
7337 //
7338 BasicBlock::iterator It = New;
7339 while (isa<AllocationInst>(*It)) ++It;
7340
7341 // Now that I is pointing to the first non-allocation-inst in the block,
7342 // insert our getelementptr instruction...
7343 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007344 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7345 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7346 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007347
7348 // Now make everything use the getelementptr instead of the original
7349 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007350 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007351 } else if (isa<UndefValue>(AI.getArraySize())) {
7352 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007353 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007354
7355 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7356 // Note that we only do this for alloca's, because malloc should allocate and
7357 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007358 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007359 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007360 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7361
Chris Lattner1085bdf2002-11-04 16:18:53 +00007362 return 0;
7363}
7364
Chris Lattner8427bff2003-12-07 01:24:23 +00007365Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7366 Value *Op = FI.getOperand(0);
7367
7368 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7369 if (CastInst *CI = dyn_cast<CastInst>(Op))
7370 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7371 FI.setOperand(0, CI->getOperand(0));
7372 return &FI;
7373 }
7374
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007375 // free undef -> unreachable.
7376 if (isa<UndefValue>(Op)) {
7377 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007378 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007379 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7380 return EraseInstFromFunction(FI);
7381 }
7382
Chris Lattnerf3a36602004-02-28 04:57:37 +00007383 // If we have 'free null' delete the instruction. This can happen in stl code
7384 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007385 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007386 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007387
Chris Lattner8427bff2003-12-07 01:24:23 +00007388 return 0;
7389}
7390
7391
Chris Lattner72684fe2005-01-31 05:51:45 +00007392/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007393static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7394 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007395 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007396
7397 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007398 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007399 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007400
Chris Lattnerebca4762006-04-02 05:37:12 +00007401 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7402 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007403 // If the source is an array, the code below will not succeed. Check to
7404 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7405 // constants.
7406 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7407 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7408 if (ASrcTy->getNumElements() != 0) {
7409 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7410 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7411 SrcTy = cast<PointerType>(CastOp->getType());
7412 SrcPTy = SrcTy->getElementType();
7413 }
7414
Chris Lattnerebca4762006-04-02 05:37:12 +00007415 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7416 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007417 // Do not allow turning this into a load of an integer, which is then
7418 // casted to a pointer, this pessimizes pointer analysis a lot.
7419 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007420 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007421 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007422
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007423 // Okay, we are casting from one integer or pointer type to another of
7424 // the same size. Instead of casting the pointer before the load, cast
7425 // the result of the loaded value.
7426 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7427 CI->getName(),
7428 LI.isVolatile()),LI);
7429 // Now cast the result of the load.
7430 return new CastInst(NewLoad, LI.getType());
7431 }
Chris Lattner35e24772004-07-13 01:49:43 +00007432 }
7433 }
7434 return 0;
7435}
7436
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007437/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007438/// from this value cannot trap. If it is not obviously safe to load from the
7439/// specified pointer, we do a quick local scan of the basic block containing
7440/// ScanFrom, to determine if the address is already accessed.
7441static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7442 // If it is an alloca or global variable, it is always safe to load from.
7443 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7444
7445 // Otherwise, be a little bit agressive by scanning the local block where we
7446 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007447 // from/to. If so, the previous load or store would have already trapped,
7448 // so there is no harm doing an extra load (also, CSE will later eliminate
7449 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007450 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7451
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007452 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007453 --BBI;
7454
7455 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7456 if (LI->getOperand(0) == V) return true;
7457 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7458 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007459
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007460 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007461 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007462}
7463
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007464Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7465 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007466
Chris Lattnera9d84e32005-05-01 04:24:53 +00007467 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007468 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007469 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7470 return Res;
7471
7472 // None of the following transforms are legal for volatile loads.
7473 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007474
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007475 if (&LI.getParent()->front() != &LI) {
7476 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007477 // If the instruction immediately before this is a store to the same
7478 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007479 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7480 if (SI->getOperand(1) == LI.getOperand(0))
7481 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007482 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7483 if (LIB->getOperand(0) == LI.getOperand(0))
7484 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007485 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007486
7487 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7488 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7489 isa<UndefValue>(GEPI->getOperand(0))) {
7490 // Insert a new store to null instruction before the load to indicate
7491 // that this code is not reachable. We do this instead of inserting
7492 // an unreachable instruction directly because we cannot modify the
7493 // CFG.
7494 new StoreInst(UndefValue::get(LI.getType()),
7495 Constant::getNullValue(Op->getType()), &LI);
7496 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7497 }
7498
Chris Lattner81a7a232004-10-16 18:11:37 +00007499 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007500 // load null/undef -> undef
7501 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007502 // Insert a new store to null instruction before the load to indicate that
7503 // this code is not reachable. We do this instead of inserting an
7504 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007505 new StoreInst(UndefValue::get(LI.getType()),
7506 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007507 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007508 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007509
Chris Lattner81a7a232004-10-16 18:11:37 +00007510 // Instcombine load (constant global) into the value loaded.
7511 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7512 if (GV->isConstant() && !GV->isExternal())
7513 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007514
Chris Lattner81a7a232004-10-16 18:11:37 +00007515 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7516 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7517 if (CE->getOpcode() == Instruction::GetElementPtr) {
7518 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7519 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007520 if (Constant *V =
7521 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007522 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007523 if (CE->getOperand(0)->isNullValue()) {
7524 // Insert a new store to null instruction before the load to indicate
7525 // that this code is not reachable. We do this instead of inserting
7526 // an unreachable instruction directly because we cannot modify the
7527 // CFG.
7528 new StoreInst(UndefValue::get(LI.getType()),
7529 Constant::getNullValue(Op->getType()), &LI);
7530 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7531 }
7532
Chris Lattner81a7a232004-10-16 18:11:37 +00007533 } else if (CE->getOpcode() == Instruction::Cast) {
7534 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7535 return Res;
7536 }
7537 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007538
Chris Lattnera9d84e32005-05-01 04:24:53 +00007539 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007540 // Change select and PHI nodes to select values instead of addresses: this
7541 // helps alias analysis out a lot, allows many others simplifications, and
7542 // exposes redundancy in the code.
7543 //
7544 // Note that we cannot do the transformation unless we know that the
7545 // introduced loads cannot trap! Something like this is valid as long as
7546 // the condition is always false: load (select bool %C, int* null, int* %G),
7547 // but it would not be valid if we transformed it to load from null
7548 // unconditionally.
7549 //
7550 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7551 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007552 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7553 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007554 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007555 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007556 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007557 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007558 return new SelectInst(SI->getCondition(), V1, V2);
7559 }
7560
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007561 // load (select (cond, null, P)) -> load P
7562 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7563 if (C->isNullValue()) {
7564 LI.setOperand(0, SI->getOperand(2));
7565 return &LI;
7566 }
7567
7568 // load (select (cond, P, null)) -> load P
7569 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7570 if (C->isNullValue()) {
7571 LI.setOperand(0, SI->getOperand(1));
7572 return &LI;
7573 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007574 }
7575 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007576 return 0;
7577}
7578
Chris Lattner72684fe2005-01-31 05:51:45 +00007579/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7580/// when possible.
7581static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7582 User *CI = cast<User>(SI.getOperand(1));
7583 Value *CastOp = CI->getOperand(0);
7584
7585 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7586 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7587 const Type *SrcPTy = SrcTy->getElementType();
7588
7589 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7590 // If the source is an array, the code below will not succeed. Check to
7591 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7592 // constants.
7593 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7594 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7595 if (ASrcTy->getNumElements() != 0) {
7596 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7597 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7598 SrcTy = cast<PointerType>(CastOp->getType());
7599 SrcPTy = SrcTy->getElementType();
7600 }
7601
7602 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007603 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007604 IC.getTargetData().getTypeSize(DestPTy)) {
7605
7606 // Okay, we are casting from one integer or pointer type to another of
7607 // the same size. Instead of casting the pointer before the store, cast
7608 // the value to be stored.
7609 Value *NewCast;
7610 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7611 NewCast = ConstantExpr::getCast(C, SrcPTy);
7612 else
7613 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7614 SrcPTy,
7615 SI.getOperand(0)->getName()+".c"), SI);
7616
7617 return new StoreInst(NewCast, CastOp);
7618 }
7619 }
7620 }
7621 return 0;
7622}
7623
Chris Lattner31f486c2005-01-31 05:36:43 +00007624Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7625 Value *Val = SI.getOperand(0);
7626 Value *Ptr = SI.getOperand(1);
7627
7628 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007629 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007630 ++NumCombined;
7631 return 0;
7632 }
7633
Chris Lattner5997cf92006-02-08 03:25:32 +00007634 // Do really simple DSE, to catch cases where there are several consequtive
7635 // stores to the same location, separated by a few arithmetic operations. This
7636 // situation often occurs with bitfield accesses.
7637 BasicBlock::iterator BBI = &SI;
7638 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7639 --ScanInsts) {
7640 --BBI;
7641
7642 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7643 // Prev store isn't volatile, and stores to the same location?
7644 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7645 ++NumDeadStore;
7646 ++BBI;
7647 EraseInstFromFunction(*PrevSI);
7648 continue;
7649 }
7650 break;
7651 }
7652
Chris Lattnerdab43b22006-05-26 19:19:20 +00007653 // If this is a load, we have to stop. However, if the loaded value is from
7654 // the pointer we're loading and is producing the pointer we're storing,
7655 // then *this* store is dead (X = load P; store X -> P).
7656 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7657 if (LI == Val && LI->getOperand(0) == Ptr) {
7658 EraseInstFromFunction(SI);
7659 ++NumCombined;
7660 return 0;
7661 }
7662 // Otherwise, this is a load from some other location. Stores before it
7663 // may not be dead.
7664 break;
7665 }
7666
Chris Lattner5997cf92006-02-08 03:25:32 +00007667 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007668 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007669 break;
7670 }
7671
7672
7673 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007674
7675 // store X, null -> turns into 'unreachable' in SimplifyCFG
7676 if (isa<ConstantPointerNull>(Ptr)) {
7677 if (!isa<UndefValue>(Val)) {
7678 SI.setOperand(0, UndefValue::get(Val->getType()));
7679 if (Instruction *U = dyn_cast<Instruction>(Val))
7680 WorkList.push_back(U); // Dropped a use.
7681 ++NumCombined;
7682 }
7683 return 0; // Do not modify these!
7684 }
7685
7686 // store undef, Ptr -> noop
7687 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007688 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007689 ++NumCombined;
7690 return 0;
7691 }
7692
Chris Lattner72684fe2005-01-31 05:51:45 +00007693 // If the pointer destination is a cast, see if we can fold the cast into the
7694 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00007695 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00007696 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7697 return Res;
7698 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7699 if (CE->getOpcode() == Instruction::Cast)
7700 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7701 return Res;
7702
Chris Lattner219175c2005-09-12 23:23:25 +00007703
7704 // If this store is the last instruction in the basic block, and if the block
7705 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007706 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007707 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7708 if (BI->isUnconditional()) {
7709 // Check to see if the successor block has exactly two incoming edges. If
7710 // so, see if the other predecessor contains a store to the same location.
7711 // if so, insert a PHI node (if needed) and move the stores down.
7712 BasicBlock *Dest = BI->getSuccessor(0);
7713
7714 pred_iterator PI = pred_begin(Dest);
7715 BasicBlock *Other = 0;
7716 if (*PI != BI->getParent())
7717 Other = *PI;
7718 ++PI;
7719 if (PI != pred_end(Dest)) {
7720 if (*PI != BI->getParent())
7721 if (Other)
7722 Other = 0;
7723 else
7724 Other = *PI;
7725 if (++PI != pred_end(Dest))
7726 Other = 0;
7727 }
7728 if (Other) { // If only one other pred...
7729 BBI = Other->getTerminator();
7730 // Make sure this other block ends in an unconditional branch and that
7731 // there is an instruction before the branch.
7732 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7733 BBI != Other->begin()) {
7734 --BBI;
7735 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7736
7737 // If this instruction is a store to the same location.
7738 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7739 // Okay, we know we can perform this transformation. Insert a PHI
7740 // node now if we need it.
7741 Value *MergedVal = OtherStore->getOperand(0);
7742 if (MergedVal != SI.getOperand(0)) {
7743 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7744 PN->reserveOperandSpace(2);
7745 PN->addIncoming(SI.getOperand(0), SI.getParent());
7746 PN->addIncoming(OtherStore->getOperand(0), Other);
7747 MergedVal = InsertNewInstBefore(PN, Dest->front());
7748 }
7749
7750 // Advance to a place where it is safe to insert the new store and
7751 // insert it.
7752 BBI = Dest->begin();
7753 while (isa<PHINode>(BBI)) ++BBI;
7754 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7755 OtherStore->isVolatile()), *BBI);
7756
7757 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007758 EraseInstFromFunction(SI);
7759 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007760 ++NumCombined;
7761 return 0;
7762 }
7763 }
7764 }
7765 }
7766
Chris Lattner31f486c2005-01-31 05:36:43 +00007767 return 0;
7768}
7769
7770
Chris Lattner9eef8a72003-06-04 04:46:00 +00007771Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7772 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007773 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007774 BasicBlock *TrueDest;
7775 BasicBlock *FalseDest;
7776 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7777 !isa<Constant>(X)) {
7778 // Swap Destinations and condition...
7779 BI.setCondition(X);
7780 BI.setSuccessor(0, FalseDest);
7781 BI.setSuccessor(1, TrueDest);
7782 return &BI;
7783 }
7784
7785 // Cannonicalize setne -> seteq
7786 Instruction::BinaryOps Op; Value *Y;
7787 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7788 TrueDest, FalseDest)))
7789 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7790 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7791 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7792 std::string Name = I->getName(); I->setName("");
7793 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7794 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007795 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007796 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007797 BI.setSuccessor(0, FalseDest);
7798 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007799 removeFromWorkList(I);
7800 I->getParent()->getInstList().erase(I);
7801 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007802 return &BI;
7803 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007804
Chris Lattner9eef8a72003-06-04 04:46:00 +00007805 return 0;
7806}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007807
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007808Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7809 Value *Cond = SI.getCondition();
7810 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7811 if (I->getOpcode() == Instruction::Add)
7812 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7813 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7814 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007815 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007816 AddRHS));
7817 SI.setOperand(0, I->getOperand(0));
7818 WorkList.push_back(I);
7819 return &SI;
7820 }
7821 }
7822 return 0;
7823}
7824
Chris Lattner6bc98652006-03-05 00:22:33 +00007825/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7826/// is to leave as a vector operation.
7827static bool CheapToScalarize(Value *V, bool isConstant) {
7828 if (isa<ConstantAggregateZero>(V))
7829 return true;
7830 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7831 if (isConstant) return true;
7832 // If all elts are the same, we can extract.
7833 Constant *Op0 = C->getOperand(0);
7834 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7835 if (C->getOperand(i) != Op0)
7836 return false;
7837 return true;
7838 }
7839 Instruction *I = dyn_cast<Instruction>(V);
7840 if (!I) return false;
7841
7842 // Insert element gets simplified to the inserted element or is deleted if
7843 // this is constant idx extract element and its a constant idx insertelt.
7844 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7845 isa<ConstantInt>(I->getOperand(2)))
7846 return true;
7847 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7848 return true;
7849 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7850 if (BO->hasOneUse() &&
7851 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7852 CheapToScalarize(BO->getOperand(1), isConstant)))
7853 return true;
7854
7855 return false;
7856}
7857
Chris Lattner12249be2006-05-25 23:48:38 +00007858/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7859/// elements into values that are larger than the #elts in the input.
7860static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7861 unsigned NElts = SVI->getType()->getNumElements();
7862 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7863 return std::vector<unsigned>(NElts, 0);
7864 if (isa<UndefValue>(SVI->getOperand(2)))
7865 return std::vector<unsigned>(NElts, 2*NElts);
7866
7867 std::vector<unsigned> Result;
7868 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7869 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7870 if (isa<UndefValue>(CP->getOperand(i)))
7871 Result.push_back(NElts*2); // undef -> 8
7872 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007873 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00007874 return Result;
7875}
7876
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007877/// FindScalarElement - Given a vector and an element number, see if the scalar
7878/// value is already around as a register, for example if it were inserted then
7879/// extracted from the vector.
7880static Value *FindScalarElement(Value *V, unsigned EltNo) {
7881 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7882 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007883 unsigned Width = PTy->getNumElements();
7884 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007885 return UndefValue::get(PTy->getElementType());
7886
7887 if (isa<UndefValue>(V))
7888 return UndefValue::get(PTy->getElementType());
7889 else if (isa<ConstantAggregateZero>(V))
7890 return Constant::getNullValue(PTy->getElementType());
7891 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7892 return CP->getOperand(EltNo);
7893 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7894 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007895 if (!isa<ConstantInt>(III->getOperand(2)))
7896 return 0;
7897 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007898
7899 // If this is an insert to the element we are looking for, return the
7900 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007901 if (EltNo == IIElt)
7902 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007903
7904 // Otherwise, the insertelement doesn't modify the value, recurse on its
7905 // vector input.
7906 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007907 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007908 unsigned InEl = getShuffleMask(SVI)[EltNo];
7909 if (InEl < Width)
7910 return FindScalarElement(SVI->getOperand(0), InEl);
7911 else if (InEl < Width*2)
7912 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7913 else
7914 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007915 }
7916
7917 // Otherwise, we don't know.
7918 return 0;
7919}
7920
Robert Bocchinoa8352962006-01-13 22:48:06 +00007921Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007922
Chris Lattner92346c32006-03-31 18:25:14 +00007923 // If packed val is undef, replace extract with scalar undef.
7924 if (isa<UndefValue>(EI.getOperand(0)))
7925 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7926
7927 // If packed val is constant 0, replace extract with scalar 0.
7928 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7929 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7930
Robert Bocchinoa8352962006-01-13 22:48:06 +00007931 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7932 // If packed val is constant with uniform operands, replace EI
7933 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007934 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007935 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007936 if (C->getOperand(i) != op0) {
7937 op0 = 0;
7938 break;
7939 }
7940 if (op0)
7941 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007942 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007943
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007944 // If extracting a specified index from the vector, see if we can recursively
7945 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007946 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00007947 // This instruction only demands the single element from the input vector.
7948 // If the input vector has a single use, simplify it based on this use
7949 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007950 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00007951 if (EI.getOperand(0)->hasOneUse()) {
7952 uint64_t UndefElts;
7953 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00007954 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00007955 UndefElts)) {
7956 EI.setOperand(0, V);
7957 return &EI;
7958 }
7959 }
7960
Reid Spencere0fc4df2006-10-20 07:07:24 +00007961 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007962 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007963 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007964
Chris Lattner83f65782006-05-25 22:53:38 +00007965 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007966 if (I->hasOneUse()) {
7967 // Push extractelement into predecessor operation if legal and
7968 // profitable to do so
7969 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007970 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7971 if (CheapToScalarize(BO, isConstantElt)) {
7972 ExtractElementInst *newEI0 =
7973 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7974 EI.getName()+".lhs");
7975 ExtractElementInst *newEI1 =
7976 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7977 EI.getName()+".rhs");
7978 InsertNewInstBefore(newEI0, EI);
7979 InsertNewInstBefore(newEI1, EI);
7980 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7981 }
Reid Spencerde46e482006-11-02 20:25:50 +00007982 } else if (isa<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007983 Value *Ptr = InsertCastBefore(I->getOperand(0),
7984 PointerType::get(EI.getType()), EI);
7985 GetElementPtrInst *GEP =
7986 new GetElementPtrInst(Ptr, EI.getOperand(1),
7987 I->getName() + ".gep");
7988 InsertNewInstBefore(GEP, EI);
7989 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007990 }
7991 }
7992 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7993 // Extracting the inserted element?
7994 if (IE->getOperand(2) == EI.getOperand(1))
7995 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7996 // If the inserted and extracted elements are constants, they must not
7997 // be the same value, extract from the pre-inserted value instead.
7998 if (isa<Constant>(IE->getOperand(2)) &&
7999 isa<Constant>(EI.getOperand(1))) {
8000 AddUsesToWorkList(EI);
8001 EI.setOperand(0, IE->getOperand(0));
8002 return &EI;
8003 }
8004 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8005 // If this is extracting an element from a shufflevector, figure out where
8006 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008007 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8008 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008009 Value *Src;
8010 if (SrcIdx < SVI->getType()->getNumElements())
8011 Src = SVI->getOperand(0);
8012 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8013 SrcIdx -= SVI->getType()->getNumElements();
8014 Src = SVI->getOperand(1);
8015 } else {
8016 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008017 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008018 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008019 }
8020 }
Chris Lattner83f65782006-05-25 22:53:38 +00008021 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008022 return 0;
8023}
8024
Chris Lattner90951862006-04-16 00:51:47 +00008025/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8026/// elements from either LHS or RHS, return the shuffle mask and true.
8027/// Otherwise, return false.
8028static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8029 std::vector<Constant*> &Mask) {
8030 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8031 "Invalid CollectSingleShuffleElements");
8032 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8033
8034 if (isa<UndefValue>(V)) {
8035 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8036 return true;
8037 } else if (V == LHS) {
8038 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008039 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008040 return true;
8041 } else if (V == RHS) {
8042 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008043 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008044 return true;
8045 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8046 // If this is an insert of an extract from some other vector, include it.
8047 Value *VecOp = IEI->getOperand(0);
8048 Value *ScalarOp = IEI->getOperand(1);
8049 Value *IdxOp = IEI->getOperand(2);
8050
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008051 if (!isa<ConstantInt>(IdxOp))
8052 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008053 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008054
8055 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8056 // Okay, we can handle this if the vector we are insertinting into is
8057 // transitively ok.
8058 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8059 // If so, update the mask to reflect the inserted undef.
8060 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8061 return true;
8062 }
8063 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8064 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008065 EI->getOperand(0)->getType() == V->getType()) {
8066 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008067 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008068
8069 // This must be extracting from either LHS or RHS.
8070 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8071 // Okay, we can handle this if the vector we are insertinting into is
8072 // transitively ok.
8073 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8074 // If so, update the mask to reflect the inserted value.
8075 if (EI->getOperand(0) == LHS) {
8076 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008077 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008078 } else {
8079 assert(EI->getOperand(0) == RHS);
8080 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008081 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008082
8083 }
8084 return true;
8085 }
8086 }
8087 }
8088 }
8089 }
8090 // TODO: Handle shufflevector here!
8091
8092 return false;
8093}
8094
8095/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8096/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8097/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008098static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008099 Value *&RHS) {
8100 assert(isa<PackedType>(V->getType()) &&
8101 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008102 "Invalid shuffle!");
8103 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8104
8105 if (isa<UndefValue>(V)) {
8106 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8107 return V;
8108 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008109 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008110 return V;
8111 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8112 // If this is an insert of an extract from some other vector, include it.
8113 Value *VecOp = IEI->getOperand(0);
8114 Value *ScalarOp = IEI->getOperand(1);
8115 Value *IdxOp = IEI->getOperand(2);
8116
8117 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8118 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8119 EI->getOperand(0)->getType() == V->getType()) {
8120 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008121 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8122 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008123
8124 // Either the extracted from or inserted into vector must be RHSVec,
8125 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008126 if (EI->getOperand(0) == RHS || RHS == 0) {
8127 RHS = EI->getOperand(0);
8128 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008129 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008130 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008131 return V;
8132 }
8133
Chris Lattner90951862006-04-16 00:51:47 +00008134 if (VecOp == RHS) {
8135 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008136 // Everything but the extracted element is replaced with the RHS.
8137 for (unsigned i = 0; i != NumElts; ++i) {
8138 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008139 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008140 }
8141 return V;
8142 }
Chris Lattner90951862006-04-16 00:51:47 +00008143
8144 // If this insertelement is a chain that comes from exactly these two
8145 // vectors, return the vector and the effective shuffle.
8146 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8147 return EI->getOperand(0);
8148
Chris Lattner39fac442006-04-15 01:39:45 +00008149 }
8150 }
8151 }
Chris Lattner90951862006-04-16 00:51:47 +00008152 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008153
8154 // Otherwise, can't do anything fancy. Return an identity vector.
8155 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008156 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008157 return V;
8158}
8159
8160Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8161 Value *VecOp = IE.getOperand(0);
8162 Value *ScalarOp = IE.getOperand(1);
8163 Value *IdxOp = IE.getOperand(2);
8164
8165 // If the inserted element was extracted from some other vector, and if the
8166 // indexes are constant, try to turn this into a shufflevector operation.
8167 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8168 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8169 EI->getOperand(0)->getType() == IE.getType()) {
8170 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008171 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8172 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008173
8174 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8175 return ReplaceInstUsesWith(IE, VecOp);
8176
8177 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8178 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8179
8180 // If we are extracting a value from a vector, then inserting it right
8181 // back into the same place, just use the input vector.
8182 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8183 return ReplaceInstUsesWith(IE, VecOp);
8184
8185 // We could theoretically do this for ANY input. However, doing so could
8186 // turn chains of insertelement instructions into a chain of shufflevector
8187 // instructions, and right now we do not merge shufflevectors. As such,
8188 // only do this in a situation where it is clear that there is benefit.
8189 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8190 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8191 // the values of VecOp, except then one read from EIOp0.
8192 // Build a new shuffle mask.
8193 std::vector<Constant*> Mask;
8194 if (isa<UndefValue>(VecOp))
8195 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8196 else {
8197 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008198 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008199 NumVectorElts));
8200 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008201 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008202 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8203 ConstantPacked::get(Mask));
8204 }
8205
8206 // If this insertelement isn't used by some other insertelement, turn it
8207 // (and any insertelements it points to), into one big shuffle.
8208 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8209 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008210 Value *RHS = 0;
8211 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8212 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8213 // We now have a shuffle of LHS, RHS, Mask.
8214 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008215 }
8216 }
8217 }
8218
8219 return 0;
8220}
8221
8222
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008223Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8224 Value *LHS = SVI.getOperand(0);
8225 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008226 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008227
8228 bool MadeChange = false;
8229
Chris Lattner2deeaea2006-10-05 06:55:50 +00008230 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008231 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008232 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8233
Chris Lattner39fac442006-04-15 01:39:45 +00008234 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8235 // the undef, change them to undefs.
8236
Chris Lattner12249be2006-05-25 23:48:38 +00008237 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8238 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8239 if (LHS == RHS || isa<UndefValue>(LHS)) {
8240 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008241 // shuffle(undef,undef,mask) -> undef.
8242 return ReplaceInstUsesWith(SVI, LHS);
8243 }
8244
Chris Lattner12249be2006-05-25 23:48:38 +00008245 // Remap any references to RHS to use LHS.
8246 std::vector<Constant*> Elts;
8247 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008248 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008249 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008250 else {
8251 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8252 (Mask[i] < e && isa<UndefValue>(LHS)))
8253 Mask[i] = 2*e; // Turn into undef.
8254 else
8255 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008256 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008257 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008258 }
Chris Lattner12249be2006-05-25 23:48:38 +00008259 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008260 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008261 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008262 LHS = SVI.getOperand(0);
8263 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008264 MadeChange = true;
8265 }
8266
Chris Lattner0e477162006-05-26 00:29:06 +00008267 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008268 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008269
Chris Lattner12249be2006-05-25 23:48:38 +00008270 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8271 if (Mask[i] >= e*2) continue; // Ignore undef values.
8272 // Is this an identity shuffle of the LHS value?
8273 isLHSID &= (Mask[i] == i);
8274
8275 // Is this an identity shuffle of the RHS value?
8276 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008277 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008278
Chris Lattner12249be2006-05-25 23:48:38 +00008279 // Eliminate identity shuffles.
8280 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8281 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008282
Chris Lattner0e477162006-05-26 00:29:06 +00008283 // If the LHS is a shufflevector itself, see if we can combine it with this
8284 // one without producing an unusual shuffle. Here we are really conservative:
8285 // we are absolutely afraid of producing a shuffle mask not in the input
8286 // program, because the code gen may not be smart enough to turn a merged
8287 // shuffle into two specific shuffles: it may produce worse code. As such,
8288 // we only merge two shuffles if the result is one of the two input shuffle
8289 // masks. In this case, merging the shuffles just removes one instruction,
8290 // which we know is safe. This is good for things like turning:
8291 // (splat(splat)) -> splat.
8292 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8293 if (isa<UndefValue>(RHS)) {
8294 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8295
8296 std::vector<unsigned> NewMask;
8297 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8298 if (Mask[i] >= 2*e)
8299 NewMask.push_back(2*e);
8300 else
8301 NewMask.push_back(LHSMask[Mask[i]]);
8302
8303 // If the result mask is equal to the src shuffle or this shuffle mask, do
8304 // the replacement.
8305 if (NewMask == LHSMask || NewMask == Mask) {
8306 std::vector<Constant*> Elts;
8307 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8308 if (NewMask[i] >= e*2) {
8309 Elts.push_back(UndefValue::get(Type::UIntTy));
8310 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008311 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008312 }
8313 }
8314 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8315 LHSSVI->getOperand(1),
8316 ConstantPacked::get(Elts));
8317 }
8318 }
8319 }
8320
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008321 return MadeChange ? &SVI : 0;
8322}
8323
8324
Robert Bocchinoa8352962006-01-13 22:48:06 +00008325
Chris Lattner99f48c62002-09-02 04:59:56 +00008326void InstCombiner::removeFromWorkList(Instruction *I) {
8327 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8328 WorkList.end());
8329}
8330
Chris Lattner39c98bb2004-12-08 23:43:58 +00008331
8332/// TryToSinkInstruction - Try to move the specified instruction from its
8333/// current block into the beginning of DestBlock, which can only happen if it's
8334/// safe to move the instruction past all of the instructions between it and the
8335/// end of its block.
8336static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8337 assert(I->hasOneUse() && "Invariants didn't hold!");
8338
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008339 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8340 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008341
Chris Lattner39c98bb2004-12-08 23:43:58 +00008342 // Do not sink alloca instructions out of the entry block.
8343 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8344 return false;
8345
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008346 // We can only sink load instructions if there is nothing between the load and
8347 // the end of block that could change the value.
8348 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008349 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8350 Scan != E; ++Scan)
8351 if (Scan->mayWriteToMemory())
8352 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008353 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008354
8355 BasicBlock::iterator InsertPos = DestBlock->begin();
8356 while (isa<PHINode>(InsertPos)) ++InsertPos;
8357
Chris Lattner9f269e42005-08-08 19:11:57 +00008358 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008359 ++NumSunkInst;
8360 return true;
8361}
8362
Chris Lattner1443bc52006-05-11 17:11:52 +00008363/// OptimizeConstantExpr - Given a constant expression and target data layout
8364/// information, symbolically evaluation the constant expr to something simpler
8365/// if possible.
8366static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8367 if (!TD) return CE;
8368
8369 Constant *Ptr = CE->getOperand(0);
8370 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8371 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8372 // If this is a constant expr gep that is effectively computing an
8373 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8374 bool isFoldableGEP = true;
8375 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8376 if (!isa<ConstantInt>(CE->getOperand(i)))
8377 isFoldableGEP = false;
8378 if (isFoldableGEP) {
8379 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8380 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008381 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008382 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8383 return ConstantExpr::getCast(C, CE->getType());
8384 }
8385 }
8386
8387 return CE;
8388}
8389
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008390
8391/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8392/// all reachable code to the worklist.
8393///
8394/// This has a couple of tricks to make the code faster and more powerful. In
8395/// particular, we constant fold and DCE instructions as we go, to avoid adding
8396/// them to the worklist (this significantly speeds up instcombine on code where
8397/// many instructions are dead or constant). Additionally, if we find a branch
8398/// whose condition is a known constant, we only visit the reachable successors.
8399///
8400static void AddReachableCodeToWorklist(BasicBlock *BB,
8401 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008402 std::vector<Instruction*> &WorkList,
8403 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008404 // We have now visited this block! If we've already been here, bail out.
8405 if (!Visited.insert(BB).second) return;
8406
8407 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8408 Instruction *Inst = BBI++;
8409
8410 // DCE instruction if trivially dead.
8411 if (isInstructionTriviallyDead(Inst)) {
8412 ++NumDeadInst;
8413 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8414 Inst->eraseFromParent();
8415 continue;
8416 }
8417
8418 // ConstantProp instruction if trivially constant.
8419 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008420 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8421 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008422 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8423 Inst->replaceAllUsesWith(C);
8424 ++NumConstProp;
8425 Inst->eraseFromParent();
8426 continue;
8427 }
8428
8429 WorkList.push_back(Inst);
8430 }
8431
8432 // Recursively visit successors. If this is a branch or switch on a constant,
8433 // only visit the reachable successor.
8434 TerminatorInst *TI = BB->getTerminator();
8435 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8436 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8437 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008438 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8439 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008440 return;
8441 }
8442 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8443 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8444 // See if this is an explicit destination.
8445 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8446 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008447 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008448 return;
8449 }
8450
8451 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008452 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008453 return;
8454 }
8455 }
8456
8457 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008458 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008459}
8460
Chris Lattner113f4f42002-06-25 16:13:24 +00008461bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008462 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008463 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008464
Chris Lattner4ed40f72005-07-07 20:40:38 +00008465 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008466 // Do a depth-first traversal of the function, populate the worklist with
8467 // the reachable instructions. Ignore blocks that are not reachable. Keep
8468 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008469 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008470 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008471
Chris Lattner4ed40f72005-07-07 20:40:38 +00008472 // Do a quick scan over the function. If we find any blocks that are
8473 // unreachable, remove any instructions inside of them. This prevents
8474 // the instcombine code from having to deal with some bad special cases.
8475 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8476 if (!Visited.count(BB)) {
8477 Instruction *Term = BB->getTerminator();
8478 while (Term != BB->begin()) { // Remove instrs bottom-up
8479 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008480
Chris Lattner4ed40f72005-07-07 20:40:38 +00008481 DEBUG(std::cerr << "IC: DCE: " << *I);
8482 ++NumDeadInst;
8483
8484 if (!I->use_empty())
8485 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8486 I->eraseFromParent();
8487 }
8488 }
8489 }
Chris Lattnerca081252001-12-14 16:52:21 +00008490
8491 while (!WorkList.empty()) {
8492 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8493 WorkList.pop_back();
8494
Chris Lattner1443bc52006-05-11 17:11:52 +00008495 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008496 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008497 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008498 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008499 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008500 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008501
Chris Lattnercd517ff2005-01-28 19:32:01 +00008502 DEBUG(std::cerr << "IC: DCE: " << *I);
8503
8504 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008505 removeFromWorkList(I);
8506 continue;
8507 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008508
Chris Lattner1443bc52006-05-11 17:11:52 +00008509 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008510 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008511 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8512 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008513 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8514
Chris Lattner1443bc52006-05-11 17:11:52 +00008515 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008516 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008517 ReplaceInstUsesWith(*I, C);
8518
Chris Lattner99f48c62002-09-02 04:59:56 +00008519 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008520 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008521 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008522 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008523 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008524
Chris Lattner39c98bb2004-12-08 23:43:58 +00008525 // See if we can trivially sink this instruction to a successor basic block.
8526 if (I->hasOneUse()) {
8527 BasicBlock *BB = I->getParent();
8528 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8529 if (UserParent != BB) {
8530 bool UserIsSuccessor = false;
8531 // See if the user is one of our successors.
8532 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8533 if (*SI == UserParent) {
8534 UserIsSuccessor = true;
8535 break;
8536 }
8537
8538 // If the user is one of our immediate successors, and if that successor
8539 // only has us as a predecessors (we'd have to split the critical edge
8540 // otherwise), we can keep going.
8541 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8542 next(pred_begin(UserParent)) == pred_end(UserParent))
8543 // Okay, the CFG is simple enough, try to sink this instruction.
8544 Changed |= TryToSinkInstruction(I, UserParent);
8545 }
8546 }
8547
Chris Lattnerca081252001-12-14 16:52:21 +00008548 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008549 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008550 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008551 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008552 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008553 DEBUG(std::cerr << "IC: Old = " << *I
8554 << " New = " << *Result);
8555
Chris Lattner396dbfe2004-06-09 05:08:07 +00008556 // Everything uses the new instruction now.
8557 I->replaceAllUsesWith(Result);
8558
8559 // Push the new instruction and any users onto the worklist.
8560 WorkList.push_back(Result);
8561 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008562
8563 // Move the name to the new instruction first...
8564 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008565 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008566
8567 // Insert the new instruction into the basic block...
8568 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008569 BasicBlock::iterator InsertPos = I;
8570
8571 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8572 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8573 ++InsertPos;
8574
8575 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008576
Chris Lattner63d75af2004-05-01 23:27:23 +00008577 // Make sure that we reprocess all operands now that we reduced their
8578 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008579 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8580 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8581 WorkList.push_back(OpI);
8582
Chris Lattner396dbfe2004-06-09 05:08:07 +00008583 // Instructions can end up on the worklist more than once. Make sure
8584 // we do not process an instruction that has been deleted.
8585 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008586
8587 // Erase the old instruction.
8588 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008589 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008590 DEBUG(std::cerr << "IC: MOD = " << *I);
8591
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008592 // If the instruction was modified, it's possible that it is now dead.
8593 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008594 if (isInstructionTriviallyDead(I)) {
8595 // Make sure we process all operands now that we are reducing their
8596 // use counts.
8597 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8598 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8599 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008600
Chris Lattner63d75af2004-05-01 23:27:23 +00008601 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008602 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008603 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008604 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008605 } else {
8606 WorkList.push_back(Result);
8607 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008608 }
Chris Lattner053c0932002-05-14 15:24:07 +00008609 }
Chris Lattner260ab202002-04-18 17:39:14 +00008610 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008611 }
8612 }
8613
Chris Lattner260ab202002-04-18 17:39:14 +00008614 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008615}
8616
Brian Gaeke38b79e82004-07-27 17:43:21 +00008617FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008618 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008619}
Brian Gaeke960707c2003-11-11 22:41:34 +00008620