blob: 8e7c4b565d2d97adee2afa87ec38ef2b2babe42e [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 Spencer7e80b0b2006-10-26 06:15:43 +0000134 Instruction *commonDivTransforms(BinaryOperator &I);
135 Instruction *commonIDivTransforms(BinaryOperator &I);
136 Instruction *visitUDiv(BinaryOperator &I);
137 Instruction *visitSDiv(BinaryOperator &I);
138 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000139 Instruction *visitRem(BinaryOperator &I);
140 Instruction *visitAnd(BinaryOperator &I);
141 Instruction *visitOr (BinaryOperator &I);
142 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000143 Instruction *visitSetCondInst(SetCondInst &I);
144 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
145
Chris Lattner0798af32005-01-13 20:14:25 +0000146 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
147 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000148 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000149 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000150 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000151 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000152 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
153 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000154 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000155 Instruction *visitCallInst(CallInst &CI);
156 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000157 Instruction *visitPHINode(PHINode &PN);
158 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000159 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000160 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000161 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000162 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000163 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000164 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000165 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000166 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000167 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000168
169 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000170 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000171
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000173 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000174 bool transformConstExprCastCall(CallSite CS);
175
Chris Lattner69193f92004-04-05 01:30:19 +0000176 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 // InsertNewInstBefore - insert an instruction New before instruction Old
178 // in the program. Add the new instruction to the worklist.
179 //
Chris Lattner623826c2004-09-28 21:48:02 +0000180 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000181 assert(New && New->getParent() == 0 &&
182 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000183 BasicBlock *BB = Old.getParent();
184 BB->getInstList().insert(&Old, New); // Insert inst
185 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000186 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 }
188
Chris Lattner7e794272004-09-24 15:21:34 +0000189 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
190 /// This also adds the cast to the worklist. Finally, this returns the
191 /// cast.
192 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
193 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000194
Chris Lattnere79d2492006-04-06 19:19:17 +0000195 if (Constant *CV = dyn_cast<Constant>(V))
196 return ConstantExpr::getCast(CV, Ty);
197
Chris Lattner7e794272004-09-24 15:21:34 +0000198 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
199 WorkList.push_back(C);
200 return C;
201 }
202
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000203 // ReplaceInstUsesWith - This method is to be used when an instruction is
204 // found to be dead, replacable with another preexisting expression. Here
205 // we add all uses of I to the worklist, replace all uses of I with the new
206 // value, then return I, so that the inst combiner will know that I was
207 // modified.
208 //
209 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000210 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000211 if (&I != V) {
212 I.replaceAllUsesWith(V);
213 return &I;
214 } else {
215 // If we are replacing the instruction with itself, this must be in a
216 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000217 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000218 return &I;
219 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000220 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000221
Chris Lattner2590e512006-02-07 06:56:34 +0000222 // UpdateValueUsesWith - This method is to be used when an value is
223 // found to be replacable with another preexisting expression or was
224 // updated. Here we add all uses of I to the worklist, replace all uses of
225 // I with the new value (unless the instruction was just updated), then
226 // return true, so that the inst combiner will know that I was modified.
227 //
228 bool UpdateValueUsesWith(Value *Old, Value *New) {
229 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
230 if (Old != New)
231 Old->replaceAllUsesWith(New);
232 if (Instruction *I = dyn_cast<Instruction>(Old))
233 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000234 if (Instruction *I = dyn_cast<Instruction>(New))
235 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000236 return true;
237 }
238
Chris Lattner51ea1272004-02-28 05:22:00 +0000239 // EraseInstFromFunction - When dealing with an instruction that has side
240 // effects or produces a void value, we can't rely on DCE to delete the
241 // instruction. Instead, visit methods should return the value returned by
242 // this function.
243 Instruction *EraseInstFromFunction(Instruction &I) {
244 assert(I.use_empty() && "Cannot erase instruction that is used!");
245 AddUsesToWorkList(I);
246 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000247 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000248 return 0; // Don't do anything with FI
249 }
250
Chris Lattner3ac7c262003-08-13 20:16:26 +0000251 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000252 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
253 /// InsertBefore instruction. This is specialized a bit to avoid inserting
254 /// casts that are known to not do anything...
255 ///
256 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
257 Instruction *InsertBefore);
258
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000260 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000261 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000262
Chris Lattner0157e7f2006-02-11 09:31:47 +0000263 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
264 uint64_t &KnownZero, uint64_t &KnownOne,
265 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000266
Chris Lattner2deeaea2006-10-05 06:55:50 +0000267 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
268 uint64_t &UndefElts, unsigned Depth = 0);
269
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000270 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
271 // PHI node as operand #0, see if we can fold the instruction into the PHI
272 // (which is only possible if all operands to the PHI are constants).
273 Instruction *FoldOpIntoPhi(Instruction &I);
274
Chris Lattner7515cab2004-11-14 19:13:23 +0000275 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
276 // operator and they all are only used by the PHI, PHI together their
277 // inputs, and do the operation once, to the result of the PHI.
278 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
279
Chris Lattnerba1cb382003-09-19 17:17:26 +0000280 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
281 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000282
283 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
284 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000285 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
286 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000287 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000288 Instruction *MatchBSwap(BinaryOperator &I);
289
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000290 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000291 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000292
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000293 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000294}
295
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000296// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000297// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000298static unsigned getComplexity(Value *V) {
299 if (isa<Instruction>(V)) {
300 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000301 return 3;
302 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000303 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000304 if (isa<Argument>(V)) return 3;
305 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306}
Chris Lattner260ab202002-04-18 17:39:14 +0000307
Chris Lattner7fb29e12003-03-11 00:12:48 +0000308// isOnlyUse - Return true if this instruction will be deleted if we stop using
309// it.
310static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000311 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000312}
313
Chris Lattnere79e8542004-02-23 06:38:22 +0000314// getPromotedType - Return the specified type promoted as it would be to pass
315// though a va_arg area...
316static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000317 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000318 case Type::SByteTyID:
319 case Type::ShortTyID: return Type::IntTy;
320 case Type::UByteTyID:
321 case Type::UShortTyID: return Type::UIntTy;
322 case Type::FloatTyID: return Type::DoubleTy;
323 default: return Ty;
324 }
325}
326
Chris Lattner567b81f2005-09-13 00:40:14 +0000327/// isCast - If the specified operand is a CastInst or a constant expr cast,
328/// return the operand value, otherwise return null.
329static Value *isCast(Value *V) {
330 if (CastInst *I = dyn_cast<CastInst>(V))
331 return I->getOperand(0);
332 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
333 if (CE->getOpcode() == Instruction::Cast)
334 return CE->getOperand(0);
335 return 0;
336}
337
Chris Lattner1d441ad2006-05-06 09:00:16 +0000338enum CastType {
339 Noop = 0,
340 Truncate = 1,
341 Signext = 2,
342 Zeroext = 3
343};
344
345/// getCastType - In the future, we will split the cast instruction into these
346/// various types. Until then, we have to do the analysis here.
347static CastType getCastType(const Type *Src, const Type *Dest) {
348 assert(Src->isIntegral() && Dest->isIntegral() &&
349 "Only works on integral types!");
350 unsigned SrcSize = Src->getPrimitiveSizeInBits();
351 unsigned DestSize = Dest->getPrimitiveSizeInBits();
352
353 if (SrcSize == DestSize) return Noop;
354 if (SrcSize > DestSize) return Truncate;
355 if (Src->isSigned()) return Signext;
356 return Zeroext;
357}
358
359
360// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
361// instruction.
362//
363static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
364 const Type *DstTy, TargetData *TD) {
365
366 // It is legal to eliminate the instruction if casting A->B->A if the sizes
367 // are identical and the bits don't get reinterpreted (for example
368 // int->float->int would not be allowed).
369 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
370 return true;
371
372 // If we are casting between pointer and integer types, treat pointers as
373 // integers of the appropriate size for the code below.
374 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
375 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
376 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
377
378 // Allow free casting and conversion of sizes as long as the sign doesn't
379 // change...
380 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
381 CastType FirstCast = getCastType(SrcTy, MidTy);
382 CastType SecondCast = getCastType(MidTy, DstTy);
383
384 // Capture the effect of these two casts. If the result is a legal cast,
385 // the CastType is stored here, otherwise a special code is used.
386 static const unsigned CastResult[] = {
387 // First cast is noop
388 0, 1, 2, 3,
389 // First cast is a truncate
390 1, 1, 4, 4, // trunc->extend is not safe to eliminate
391 // First cast is a sign ext
392 2, 5, 2, 4, // signext->zeroext never ok
393 // First cast is a zero ext
394 3, 5, 3, 3,
395 };
396
397 unsigned Result = CastResult[FirstCast*4+SecondCast];
398 switch (Result) {
399 default: assert(0 && "Illegal table value!");
400 case 0:
401 case 1:
402 case 2:
403 case 3:
404 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
405 // truncates, we could eliminate more casts.
406 return (unsigned)getCastType(SrcTy, DstTy) == Result;
407 case 4:
408 return false; // Not possible to eliminate this here.
409 case 5:
410 // Sign or zero extend followed by truncate is always ok if the result
411 // is a truncate or noop.
412 CastType ResultCast = getCastType(SrcTy, DstTy);
413 if (ResultCast == Noop || ResultCast == Truncate)
414 return true;
415 // Otherwise we are still growing the value, we are only safe if the
416 // result will match the sign/zeroextendness of the result.
417 return ResultCast == FirstCast;
418 }
419 }
420
421 // If this is a cast from 'float -> double -> integer', cast from
422 // 'float -> integer' directly, as the value isn't changed by the
423 // float->double conversion.
424 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
425 DstTy->isIntegral() &&
426 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
427 return true;
428
429 // Packed type conversions don't modify bits.
430 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
431 return true;
432
433 return false;
434}
435
436/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
437/// in any code being generated. It does not require codegen if V is simple
438/// enough or if the cast can be folded into other casts.
439static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
440 if (V->getType() == Ty || isa<Constant>(V)) return false;
441
442 // If this is a noop cast, it isn't real codegen.
443 if (V->getType()->isLosslesslyConvertibleTo(Ty))
444 return false;
445
Chris Lattner99155be2006-05-25 23:24:33 +0000446 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447 if (const CastInst *CI = dyn_cast<CastInst>(V))
448 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
449 TD))
450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
458Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
459 Instruction *InsertBefore) {
460 if (V->getType() == DestTy) return V;
461 if (Constant *C = dyn_cast<Constant>(V))
462 return ConstantExpr::getCast(C, DestTy);
463
464 CastInst *CI = new CastInst(V, DestTy, V->getName());
465 InsertNewInstBefore(CI, *InsertBefore);
466 return CI;
467}
468
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000469// SimplifyCommutative - This performs a few simplifications for commutative
470// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000471//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000472// 1. Order operands such that they are listed from right (least complex) to
473// left (most complex). This puts constants before unary operators before
474// binary operators.
475//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000476// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000478//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000479bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000480 bool Changed = false;
481 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000483
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000484 if (!I.isAssociative()) return Changed;
485 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000486 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000489 Constant *Folded = ConstantExpr::get(I.getOpcode(),
490 cast<Constant>(I.getOperand(1)),
491 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492 I.setOperand(0, Op->getOperand(0));
493 I.setOperand(1, Folded);
494 return true;
495 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497 isOnlyUse(Op) && isOnlyUse(Op1)) {
498 Constant *C1 = cast<Constant>(Op->getOperand(1));
499 Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000503 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504 Op1->getOperand(0),
505 Op1->getName(), &I);
506 WorkList.push_back(New);
507 I.setOperand(0, New);
508 I.setOperand(1, Folded);
509 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000510 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000511 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000512 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000513}
Chris Lattnerca081252001-12-14 16:52:21 +0000514
Chris Lattnerbb74e222003-03-10 23:06:50 +0000515// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
516// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000518static inline Value *dyn_castNegVal(Value *V) {
519 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000520 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521
Chris Lattner9ad0d552004-12-14 20:08:06 +0000522 // Constants can be considered to be negated values if they can be folded.
523 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
524 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000526}
527
Chris Lattnerbb74e222003-03-10 23:06:50 +0000528static inline Value *dyn_castNotVal(Value *V) {
529 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000530 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000531
532 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000533 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000534 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000535 return 0;
536}
537
Chris Lattner7fb29e12003-03-11 00:12:48 +0000538// dyn_castFoldableMul - If this value is a multiply that can be folded into
539// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540// non-constant operand of the multiply, and set CST to point to the multiplier.
541// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000543static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000544 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000547 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000548 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000550 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000551 // The multiplier is really 1 << CST.
552 Constant *One = ConstantInt::get(V->getType(), 1);
553 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
554 return I->getOperand(0);
555 }
556 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000557 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000558}
Chris Lattner31ae8632002-08-14 17:51:49 +0000559
Chris Lattner0798af32005-01-13 20:14:25 +0000560/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
561/// expression, return it.
562static User *dyn_castGetElementPtr(Value *V) {
563 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
565 if (CE->getOpcode() == Instruction::GetElementPtr)
566 return cast<User>(V);
567 return false;
568}
569
Chris Lattner623826c2004-09-28 21:48:02 +0000570// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000571static ConstantInt *AddOne(ConstantInt *C) {
572 return cast<ConstantInt>(ConstantExpr::getAdd(C,
573 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000574}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000575static ConstantInt *SubOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getSub(C,
577 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000578}
579
Chris Lattner0157e7f2006-02-11 09:31:47 +0000580/// GetConstantInType - Return a ConstantInt with the specified type and value.
581///
Chris Lattneree0f2802006-02-12 02:07:56 +0000582static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000583 if (Ty->isUnsigned())
584 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000585 else if (Ty->getTypeID() == Type::BoolTyID)
586 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000587 int64_t SVal = Val;
588 SVal <<= 64-Ty->getPrimitiveSizeInBits();
589 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000590 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000591}
592
593
Chris Lattner4534dd592006-02-09 07:38:58 +0000594/// ComputeMaskedBits - Determine which of the bits specified in Mask are
595/// known to be either zero or one and return them in the KnownZero/KnownOne
596/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
597/// processing.
598static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
599 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000600 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
601 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000602 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000603 // optimized based on the contradictory assumption that it is non-zero.
604 // Because instcombine aggressively folds operations with undef args anyway,
605 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000606 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
607 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000608 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000609 KnownZero = ~KnownOne & Mask;
610 return;
611 }
612
613 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000614 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000615 return; // Limit search depth.
616
617 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000618 Instruction *I = dyn_cast<Instruction>(V);
619 if (!I) return;
620
Chris Lattnerfb296922006-05-04 17:33:35 +0000621 Mask &= V->getType()->getIntegralTypeMask();
622
Chris Lattner0157e7f2006-02-11 09:31:47 +0000623 switch (I->getOpcode()) {
624 case Instruction::And:
625 // If either the LHS or the RHS are Zero, the result is zero.
626 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
627 Mask &= ~KnownZero;
628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
629 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
630 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
631
632 // Output known-1 bits are only known if set in both the LHS & RHS.
633 KnownOne &= KnownOne2;
634 // Output known-0 are known to be clear if zero in either the LHS | RHS.
635 KnownZero |= KnownZero2;
636 return;
637 case Instruction::Or:
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
639 Mask &= ~KnownOne;
640 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
643
644 // Output known-0 bits are only known if clear in both the LHS & RHS.
645 KnownZero &= KnownZero2;
646 // Output known-1 are known to be set if set in either the LHS | RHS.
647 KnownOne |= KnownOne2;
648 return;
649 case Instruction::Xor: {
650 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
651 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
654
655 // Output known-0 bits are known if clear or set in both the LHS & RHS.
656 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
657 // Output known-1 are known to be set if set in only one of the LHS, RHS.
658 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
659 KnownZero = KnownZeroOut;
660 return;
661 }
662 case Instruction::Select:
663 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
664 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
665 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
666 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
667
668 // Only known if known in both the LHS and RHS.
669 KnownOne &= KnownOne2;
670 KnownZero &= KnownZero2;
671 return;
672 case Instruction::Cast: {
673 const Type *SrcTy = I->getOperand(0)->getType();
674 if (!SrcTy->isIntegral()) return;
675
676 // If this is an integer truncate or noop, just look in the input.
677 if (SrcTy->getPrimitiveSizeInBits() >=
678 I->getType()->getPrimitiveSizeInBits()) {
679 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000680 return;
681 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000682
Chris Lattner0157e7f2006-02-11 09:31:47 +0000683 // Sign or Zero extension. Compute the bits in the result that are not
684 // present in the input.
685 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
686 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000687
Chris Lattner0157e7f2006-02-11 09:31:47 +0000688 // Handle zero extension.
689 if (!SrcTy->isSigned()) {
690 Mask &= SrcTy->getIntegralTypeMask();
691 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
693 // The top bits are known to be zero.
694 KnownZero |= NewBits;
695 } else {
696 // Sign extension.
697 Mask &= SrcTy->getIntegralTypeMask();
698 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
699 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000700
Chris Lattner0157e7f2006-02-11 09:31:47 +0000701 // If the sign bit of the input is known set or clear, then we know the
702 // top bits of the result.
703 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
704 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000705 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000706 KnownOne &= ~NewBits;
707 } else if (KnownOne & InSignBit) { // Input sign bit known set
708 KnownOne |= NewBits;
709 KnownZero &= ~NewBits;
710 } else { // Input sign bit unknown
711 KnownZero &= ~NewBits;
712 KnownOne &= ~NewBits;
713 }
714 }
715 return;
716 }
717 case Instruction::Shl:
718 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000719 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
720 uint64_t ShiftAmt = SA->getZExtValue();
721 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000722 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000724 KnownZero <<= ShiftAmt;
725 KnownOne <<= ShiftAmt;
726 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000727 return;
728 }
729 break;
730 case Instruction::Shr:
731 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000732 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000733 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000734 uint64_t ShiftAmt = SA->getZExtValue();
735 uint64_t HighBits = (1ULL << ShiftAmt)-1;
736 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000737
738 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000739 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000740 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
741 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000742 KnownZero >>= ShiftAmt;
743 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000744 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000745 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000746 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
748 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000749 KnownZero >>= ShiftAmt;
750 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000751
752 // Handle the sign bits.
753 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000754 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755
756 if (KnownZero & SignBit) { // New bits are known zero.
757 KnownZero |= HighBits;
758 } else if (KnownOne & SignBit) { // New bits are known one.
759 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000760 }
761 }
762 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000763 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000764 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000765 }
Chris Lattner92a68652006-02-07 08:05:22 +0000766}
767
768/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
769/// this predicate to simplify operations downstream. Mask is known to be zero
770/// for bits that V cannot have.
771static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000772 uint64_t KnownZero, KnownOne;
773 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
775 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000776}
777
Chris Lattner0157e7f2006-02-11 09:31:47 +0000778/// ShrinkDemandedConstant - Check to see if the specified operand of the
779/// specified instruction is a constant integer. If so, check to see if there
780/// are any bits set in the constant that are not demanded. If so, shrink the
781/// constant and return true.
782static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
783 uint64_t Demanded) {
784 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
785 if (!OpC) return false;
786
787 // If there are no bits set that aren't demanded, nothing to do.
788 if ((~Demanded & OpC->getZExtValue()) == 0)
789 return false;
790
791 // This is producing any bits that are not needed, shrink the RHS.
792 uint64_t Val = Demanded & OpC->getZExtValue();
793 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
794 return true;
795}
796
Chris Lattneree0f2802006-02-12 02:07:56 +0000797// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
798// set of known zero and one bits, compute the maximum and minimum values that
799// could have the specified known zero and known one bits, returning them in
800// min/max.
801static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
802 uint64_t KnownZero,
803 uint64_t KnownOne,
804 int64_t &Min, int64_t &Max) {
805 uint64_t TypeBits = Ty->getIntegralTypeMask();
806 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
807
808 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
809
810 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
811 // bit if it is unknown.
812 Min = KnownOne;
813 Max = KnownOne|UnknownBits;
814
815 if (SignBit & UnknownBits) { // Sign bit is unknown
816 Min |= SignBit;
817 Max &= ~SignBit;
818 }
819
820 // Sign extend the min/max values.
821 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
822 Min = (Min << ShAmt) >> ShAmt;
823 Max = (Max << ShAmt) >> ShAmt;
824}
825
826// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
827// a set of known zero and one bits, compute the maximum and minimum values that
828// could have the specified known zero and known one bits, returning them in
829// min/max.
830static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
831 uint64_t KnownZero,
832 uint64_t KnownOne,
833 uint64_t &Min,
834 uint64_t &Max) {
835 uint64_t TypeBits = Ty->getIntegralTypeMask();
836 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
837
838 // The minimum value is when the unknown bits are all zeros.
839 Min = KnownOne;
840 // The maximum value is when the unknown bits are all ones.
841 Max = KnownOne|UnknownBits;
842}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000843
844
845/// SimplifyDemandedBits - Look at V. At this point, we know that only the
846/// DemandedMask bits of the result of V are ever used downstream. If we can
847/// use this information to simplify V, do so and return true. Otherwise,
848/// analyze the expression and return a mask of KnownOne and KnownZero bits for
849/// the expression (used to simplify the caller). The KnownZero/One bits may
850/// only be accurate for those bits in the DemandedMask.
851bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
852 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000853 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000854 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
855 // We know all of the bits for a constant!
856 KnownOne = CI->getZExtValue() & DemandedMask;
857 KnownZero = ~KnownOne & DemandedMask;
858 return false;
859 }
860
861 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000862 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000863 if (Depth != 0) { // Not at the root.
864 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
865 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000866 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000867 }
Chris Lattner2590e512006-02-07 06:56:34 +0000868 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000869 // just set the DemandedMask to all bits.
870 DemandedMask = V->getType()->getIntegralTypeMask();
871 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000872 if (V != UndefValue::get(V->getType()))
873 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
874 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000875 } else if (Depth == 6) { // Limit search depth.
876 return false;
877 }
878
879 Instruction *I = dyn_cast<Instruction>(V);
880 if (!I) return false; // Only analyze instructions.
881
Chris Lattnerfb296922006-05-04 17:33:35 +0000882 DemandedMask &= V->getType()->getIntegralTypeMask();
883
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000885 switch (I->getOpcode()) {
886 default: break;
887 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000888 // If either the LHS or the RHS are Zero, the result is zero.
889 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890 KnownZero, KnownOne, Depth+1))
891 return true;
892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
893
894 // If something is known zero on the RHS, the bits aren't demanded on the
895 // LHS.
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
897 KnownZero2, KnownOne2, Depth+1))
898 return true;
899 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
900
901 // If all of the demanded bits are known one on one side, return the other.
902 // These bits cannot contribute to the result of the 'and'.
903 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
904 return UpdateValueUsesWith(I, I->getOperand(0));
905 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
906 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000907
908 // If all of the demanded bits in the inputs are known zeros, return zero.
909 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
910 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
911
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000913 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914 return UpdateValueUsesWith(I, I);
915
916 // Output known-1 bits are only known if set in both the LHS & RHS.
917 KnownOne &= KnownOne2;
918 // Output known-0 are known to be clear if zero in either the LHS | RHS.
919 KnownZero |= KnownZero2;
920 break;
921 case Instruction::Or:
922 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
923 KnownZero, KnownOne, Depth+1))
924 return true;
925 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
926 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
927 KnownZero2, KnownOne2, Depth+1))
928 return true;
929 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
930
931 // If all of the demanded bits are known zero on one side, return the other.
932 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000933 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000934 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000935 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000936 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000937
938 // If all of the potentially set bits on one side are known to be set on
939 // the other side, just use the 'other' side.
940 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
941 (DemandedMask & (~KnownZero)))
942 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000943 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
944 (DemandedMask & (~KnownZero2)))
945 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000946
947 // If the RHS is a constant, see if we can simplify it.
948 if (ShrinkDemandedConstant(I, 1, DemandedMask))
949 return UpdateValueUsesWith(I, I);
950
951 // Output known-0 bits are only known if clear in both the LHS & RHS.
952 KnownZero &= KnownZero2;
953 // Output known-1 are known to be set if set in either the LHS | RHS.
954 KnownOne |= KnownOne2;
955 break;
956 case Instruction::Xor: {
957 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958 KnownZero, KnownOne, Depth+1))
959 return true;
960 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
961 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
962 KnownZero2, KnownOne2, Depth+1))
963 return true;
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965
966 // If all of the demanded bits are known zero on one side, return the other.
967 // These bits cannot contribute to the result of the 'xor'.
968 if ((DemandedMask & KnownZero) == DemandedMask)
969 return UpdateValueUsesWith(I, I->getOperand(0));
970 if ((DemandedMask & KnownZero2) == DemandedMask)
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // Output known-0 bits are known if clear or set in both the LHS & RHS.
974 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
975 // Output known-1 are known to be set if set in only one of the LHS, RHS.
976 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
977
978 // If all of the unknown bits are known to be zero on one side or the other
979 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000980 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000981 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
982 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
983 Instruction *Or =
984 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
985 I->getName());
986 InsertNewInstBefore(Or, *I);
987 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000988 }
989 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000990
Chris Lattner5b2edb12006-02-12 08:02:11 +0000991 // If all of the demanded bits on one side are known, and all of the set
992 // bits on that side are also known to be set on the other side, turn this
993 // into an AND, as we know the bits will be cleared.
994 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
995 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
996 if ((KnownOne & KnownOne2) == KnownOne) {
997 Constant *AndC = GetConstantInType(I->getType(),
998 ~KnownOne & DemandedMask);
999 Instruction *And =
1000 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1001 InsertNewInstBefore(And, *I);
1002 return UpdateValueUsesWith(I, And);
1003 }
1004 }
1005
Chris Lattner0157e7f2006-02-11 09:31:47 +00001006 // If the RHS is a constant, see if we can simplify it.
1007 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1008 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1009 return UpdateValueUsesWith(I, I);
1010
1011 KnownZero = KnownZeroOut;
1012 KnownOne = KnownOneOut;
1013 break;
1014 }
1015 case Instruction::Select:
1016 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1017 KnownZero, KnownOne, Depth+1))
1018 return true;
1019 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1020 KnownZero2, KnownOne2, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1024
1025 // If the operands are constants, see if we can simplify them.
1026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1027 return UpdateValueUsesWith(I, I);
1028 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1029 return UpdateValueUsesWith(I, I);
1030
1031 // Only known if known in both the LHS and RHS.
1032 KnownOne &= KnownOne2;
1033 KnownZero &= KnownZero2;
1034 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001035 case Instruction::Cast: {
1036 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001037 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001038
Chris Lattner0157e7f2006-02-11 09:31:47 +00001039 // If this is an integer truncate or noop, just look in the input.
1040 if (SrcTy->getPrimitiveSizeInBits() >=
1041 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001042 // Cast to bool is a comparison against 0, which demands all bits. We
1043 // can't propagate anything useful up.
1044 if (I->getType() == Type::BoolTy)
1045 break;
1046
Chris Lattner0157e7f2006-02-11 09:31:47 +00001047 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1048 KnownZero, KnownOne, Depth+1))
1049 return true;
1050 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1051 break;
1052 }
1053
1054 // Sign or Zero extension. Compute the bits in the result that are not
1055 // present in the input.
1056 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1057 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1058
1059 // Handle zero extension.
1060 if (!SrcTy->isSigned()) {
1061 DemandedMask &= SrcTy->getIntegralTypeMask();
1062 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1063 KnownZero, KnownOne, Depth+1))
1064 return true;
1065 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1066 // The top bits are known to be zero.
1067 KnownZero |= NewBits;
1068 } else {
1069 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001070 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1071 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1072
1073 // If any of the sign extended bits are demanded, we know that the sign
1074 // bit is demanded.
1075 if (NewBits & DemandedMask)
1076 InputDemandedBits |= InSignBit;
1077
1078 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001079 KnownZero, KnownOne, Depth+1))
1080 return true;
1081 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1082
1083 // If the sign bit of the input is known set or clear, then we know the
1084 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001085
Chris Lattner0157e7f2006-02-11 09:31:47 +00001086 // If the input sign bit is known zero, or if the NewBits are not demanded
1087 // convert this into a zero extension.
1088 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001089 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001090 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001091 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001092 I->getOperand(0)->getName());
1093 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001094 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001095 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1096 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001097 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001098 } else if (KnownOne & InSignBit) { // Input sign bit known set
1099 KnownOne |= NewBits;
1100 KnownZero &= ~NewBits;
1101 } else { // Input sign bit unknown
1102 KnownZero &= ~NewBits;
1103 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001104 }
Chris Lattner2590e512006-02-07 06:56:34 +00001105 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001106 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001107 }
Chris Lattner2590e512006-02-07 06:56:34 +00001108 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001109 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1110 uint64_t ShiftAmt = SA->getZExtValue();
1111 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001112 KnownZero, KnownOne, Depth+1))
1113 return true;
1114 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001115 KnownZero <<= ShiftAmt;
1116 KnownOne <<= ShiftAmt;
1117 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001118 }
Chris Lattner2590e512006-02-07 06:56:34 +00001119 break;
1120 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001121 // If this is an arithmetic shift right and only the low-bit is set, we can
1122 // always convert this into a logical shr, even if the shift amount is
1123 // variable. The low bit of the shift cannot be an input sign bit unless
1124 // the shift amount is >= the size of the datatype, which is undefined.
1125 if (DemandedMask == 1 && I->getType()->isSigned()) {
1126 // Convert the input to unsigned.
1127 Instruction *NewVal = new CastInst(I->getOperand(0),
1128 I->getType()->getUnsignedVersion(),
1129 I->getOperand(0)->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 // Perform the unsigned shift right.
1132 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1133 I->getName());
1134 InsertNewInstBefore(NewVal, *I);
1135 // Then cast that to the destination type.
1136 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1137 InsertNewInstBefore(NewVal, *I);
1138 return UpdateValueUsesWith(I, NewVal);
1139 }
1140
Reid Spencere0fc4df2006-10-20 07:07:24 +00001141 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1142 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001143
1144 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001145 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1146 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001147 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001148 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001149 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001150 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001151 KnownZero, KnownOne, Depth+1))
1152 return true;
1153 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001154 KnownZero &= TypeMask;
1155 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001156 KnownZero >>= ShiftAmt;
1157 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001158 KnownZero |= HighBits; // high bits known zero.
1159 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001160 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001161 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001162 KnownZero, KnownOne, Depth+1))
1163 return true;
1164 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001165 KnownZero &= TypeMask;
1166 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001167 KnownZero >>= ShiftAmt;
1168 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001169
1170 // Handle the sign bits.
1171 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001172 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001173
1174 // If the input sign bit is known to be zero, or if none of the top bits
1175 // are demanded, turn this into an unsigned shift right.
1176 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1177 // Convert the input to unsigned.
1178 Instruction *NewVal;
1179 NewVal = new CastInst(I->getOperand(0),
1180 I->getType()->getUnsignedVersion(),
1181 I->getOperand(0)->getName());
1182 InsertNewInstBefore(NewVal, *I);
1183 // Perform the unsigned shift right.
1184 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1185 InsertNewInstBefore(NewVal, *I);
1186 // Then cast that to the destination type.
1187 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1188 InsertNewInstBefore(NewVal, *I);
1189 return UpdateValueUsesWith(I, NewVal);
1190 } else if (KnownOne & SignBit) { // New bits are known one.
1191 KnownOne |= HighBits;
1192 }
Chris Lattner2590e512006-02-07 06:56:34 +00001193 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001194 }
Chris Lattner2590e512006-02-07 06:56:34 +00001195 break;
1196 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001197
1198 // If the client is only demanding bits that we know, return the known
1199 // constant.
1200 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1201 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001202 return false;
1203}
1204
Chris Lattner2deeaea2006-10-05 06:55:50 +00001205
1206/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1207/// 64 or fewer elements. DemandedElts contains the set of elements that are
1208/// actually used by the caller. This method analyzes which elements of the
1209/// operand are undef and returns that information in UndefElts.
1210///
1211/// If the information about demanded elements can be used to simplify the
1212/// operation, the operation is simplified, then the resultant value is
1213/// returned. This returns null if no change was made.
1214Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1215 uint64_t &UndefElts,
1216 unsigned Depth) {
1217 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1218 assert(VWidth <= 64 && "Vector too wide to analyze!");
1219 uint64_t EltMask = ~0ULL >> (64-VWidth);
1220 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1221 "Invalid DemandedElts!");
1222
1223 if (isa<UndefValue>(V)) {
1224 // If the entire vector is undefined, just return this info.
1225 UndefElts = EltMask;
1226 return 0;
1227 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1228 UndefElts = EltMask;
1229 return UndefValue::get(V->getType());
1230 }
1231
1232 UndefElts = 0;
1233 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1234 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1235 Constant *Undef = UndefValue::get(EltTy);
1236
1237 std::vector<Constant*> Elts;
1238 for (unsigned i = 0; i != VWidth; ++i)
1239 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1240 Elts.push_back(Undef);
1241 UndefElts |= (1ULL << i);
1242 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1243 Elts.push_back(Undef);
1244 UndefElts |= (1ULL << i);
1245 } else { // Otherwise, defined.
1246 Elts.push_back(CP->getOperand(i));
1247 }
1248
1249 // If we changed the constant, return it.
1250 Constant *NewCP = ConstantPacked::get(Elts);
1251 return NewCP != CP ? NewCP : 0;
1252 } else if (isa<ConstantAggregateZero>(V)) {
1253 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1254 // set to undef.
1255 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1256 Constant *Zero = Constant::getNullValue(EltTy);
1257 Constant *Undef = UndefValue::get(EltTy);
1258 std::vector<Constant*> Elts;
1259 for (unsigned i = 0; i != VWidth; ++i)
1260 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1261 UndefElts = DemandedElts ^ EltMask;
1262 return ConstantPacked::get(Elts);
1263 }
1264
1265 if (!V->hasOneUse()) { // Other users may use these bits.
1266 if (Depth != 0) { // Not at the root.
1267 // TODO: Just compute the UndefElts information recursively.
1268 return false;
1269 }
1270 return false;
1271 } else if (Depth == 10) { // Limit search depth.
1272 return false;
1273 }
1274
1275 Instruction *I = dyn_cast<Instruction>(V);
1276 if (!I) return false; // Only analyze instructions.
1277
1278 bool MadeChange = false;
1279 uint64_t UndefElts2;
1280 Value *TmpV;
1281 switch (I->getOpcode()) {
1282 default: break;
1283
1284 case Instruction::InsertElement: {
1285 // If this is a variable index, we don't know which element it overwrites.
1286 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001287 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001288 if (Idx == 0) {
1289 // Note that we can't propagate undef elt info, because we don't know
1290 // which elt is getting updated.
1291 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1292 UndefElts2, Depth+1);
1293 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1294 break;
1295 }
1296
1297 // If this is inserting an element that isn't demanded, remove this
1298 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001299 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001300 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1301 return AddSoonDeadInstToWorklist(*I, 0);
1302
1303 // Otherwise, the element inserted overwrites whatever was there, so the
1304 // input demanded set is simpler than the output set.
1305 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1306 DemandedElts & ~(1ULL << IdxNo),
1307 UndefElts, Depth+1);
1308 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1309
1310 // The inserted element is defined.
1311 UndefElts |= 1ULL << IdxNo;
1312 break;
1313 }
1314
1315 case Instruction::And:
1316 case Instruction::Or:
1317 case Instruction::Xor:
1318 case Instruction::Add:
1319 case Instruction::Sub:
1320 case Instruction::Mul:
1321 // div/rem demand all inputs, because they don't want divide by zero.
1322 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1323 UndefElts, Depth+1);
1324 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1325 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1326 UndefElts2, Depth+1);
1327 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1328
1329 // Output elements are undefined if both are undefined. Consider things
1330 // like undef&0. The result is known zero, not undef.
1331 UndefElts &= UndefElts2;
1332 break;
1333
1334 case Instruction::Call: {
1335 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1336 if (!II) break;
1337 switch (II->getIntrinsicID()) {
1338 default: break;
1339
1340 // Binary vector operations that work column-wise. A dest element is a
1341 // function of the corresponding input elements from the two inputs.
1342 case Intrinsic::x86_sse_sub_ss:
1343 case Intrinsic::x86_sse_mul_ss:
1344 case Intrinsic::x86_sse_min_ss:
1345 case Intrinsic::x86_sse_max_ss:
1346 case Intrinsic::x86_sse2_sub_sd:
1347 case Intrinsic::x86_sse2_mul_sd:
1348 case Intrinsic::x86_sse2_min_sd:
1349 case Intrinsic::x86_sse2_max_sd:
1350 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1351 UndefElts, Depth+1);
1352 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1353 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1354 UndefElts2, Depth+1);
1355 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1356
1357 // If only the low elt is demanded and this is a scalarizable intrinsic,
1358 // scalarize it now.
1359 if (DemandedElts == 1) {
1360 switch (II->getIntrinsicID()) {
1361 default: break;
1362 case Intrinsic::x86_sse_sub_ss:
1363 case Intrinsic::x86_sse_mul_ss:
1364 case Intrinsic::x86_sse2_sub_sd:
1365 case Intrinsic::x86_sse2_mul_sd:
1366 // TODO: Lower MIN/MAX/ABS/etc
1367 Value *LHS = II->getOperand(1);
1368 Value *RHS = II->getOperand(2);
1369 // Extract the element as scalars.
1370 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1371 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1372
1373 switch (II->getIntrinsicID()) {
1374 default: assert(0 && "Case stmts out of sync!");
1375 case Intrinsic::x86_sse_sub_ss:
1376 case Intrinsic::x86_sse2_sub_sd:
1377 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1378 II->getName()), *II);
1379 break;
1380 case Intrinsic::x86_sse_mul_ss:
1381 case Intrinsic::x86_sse2_mul_sd:
1382 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1383 II->getName()), *II);
1384 break;
1385 }
1386
1387 Instruction *New =
1388 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1389 II->getName());
1390 InsertNewInstBefore(New, *II);
1391 AddSoonDeadInstToWorklist(*II, 0);
1392 return New;
1393 }
1394 }
1395
1396 // Output elements are undefined if both are undefined. Consider things
1397 // like undef&0. The result is known zero, not undef.
1398 UndefElts &= UndefElts2;
1399 break;
1400 }
1401 break;
1402 }
1403 }
1404 return MadeChange ? I : 0;
1405}
1406
Chris Lattner623826c2004-09-28 21:48:02 +00001407// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1408// true when both operands are equal...
1409//
1410static bool isTrueWhenEqual(Instruction &I) {
1411 return I.getOpcode() == Instruction::SetEQ ||
1412 I.getOpcode() == Instruction::SetGE ||
1413 I.getOpcode() == Instruction::SetLE;
1414}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001415
1416/// AssociativeOpt - Perform an optimization on an associative operator. This
1417/// function is designed to check a chain of associative operators for a
1418/// potential to apply a certain optimization. Since the optimization may be
1419/// applicable if the expression was reassociated, this checks the chain, then
1420/// reassociates the expression as necessary to expose the optimization
1421/// opportunity. This makes use of a special Functor, which must define
1422/// 'shouldApply' and 'apply' methods.
1423///
1424template<typename Functor>
1425Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1426 unsigned Opcode = Root.getOpcode();
1427 Value *LHS = Root.getOperand(0);
1428
1429 // Quick check, see if the immediate LHS matches...
1430 if (F.shouldApply(LHS))
1431 return F.apply(Root);
1432
1433 // Otherwise, if the LHS is not of the same opcode as the root, return.
1434 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001435 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001436 // Should we apply this transform to the RHS?
1437 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1438
1439 // If not to the RHS, check to see if we should apply to the LHS...
1440 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1441 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1442 ShouldApply = true;
1443 }
1444
1445 // If the functor wants to apply the optimization to the RHS of LHSI,
1446 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1447 if (ShouldApply) {
1448 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001449
Chris Lattnerb8b97502003-08-13 19:01:45 +00001450 // Now all of the instructions are in the current basic block, go ahead
1451 // and perform the reassociation.
1452 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1453
1454 // First move the selected RHS to the LHS of the root...
1455 Root.setOperand(0, LHSI->getOperand(1));
1456
1457 // Make what used to be the LHS of the root be the user of the root...
1458 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001459 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001460 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1461 return 0;
1462 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001463 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001464 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001465 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1466 BasicBlock::iterator ARI = &Root; ++ARI;
1467 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1468 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001469
1470 // Now propagate the ExtraOperand down the chain of instructions until we
1471 // get to LHSI.
1472 while (TmpLHSI != LHSI) {
1473 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001474 // Move the instruction to immediately before the chain we are
1475 // constructing to avoid breaking dominance properties.
1476 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1477 BB->getInstList().insert(ARI, NextLHSI);
1478 ARI = NextLHSI;
1479
Chris Lattnerb8b97502003-08-13 19:01:45 +00001480 Value *NextOp = NextLHSI->getOperand(1);
1481 NextLHSI->setOperand(1, ExtraOperand);
1482 TmpLHSI = NextLHSI;
1483 ExtraOperand = NextOp;
1484 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001485
Chris Lattnerb8b97502003-08-13 19:01:45 +00001486 // Now that the instructions are reassociated, have the functor perform
1487 // the transformation...
1488 return F.apply(Root);
1489 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001490
Chris Lattnerb8b97502003-08-13 19:01:45 +00001491 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1492 }
1493 return 0;
1494}
1495
1496
1497// AddRHS - Implements: X + X --> X << 1
1498struct AddRHS {
1499 Value *RHS;
1500 AddRHS(Value *rhs) : RHS(rhs) {}
1501 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1502 Instruction *apply(BinaryOperator &Add) const {
1503 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1504 ConstantInt::get(Type::UByteTy, 1));
1505 }
1506};
1507
1508// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1509// iff C1&C2 == 0
1510struct AddMaskingAnd {
1511 Constant *C2;
1512 AddMaskingAnd(Constant *c) : C2(c) {}
1513 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001514 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001515 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001516 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 }
1518 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001519 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001520 }
1521};
1522
Chris Lattner86102b82005-01-01 16:22:27 +00001523static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001524 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001525 if (isa<CastInst>(I)) {
1526 if (Constant *SOC = dyn_cast<Constant>(SO))
1527 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001528
Chris Lattner86102b82005-01-01 16:22:27 +00001529 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1530 SO->getName() + ".cast"), I);
1531 }
1532
Chris Lattner183b3362004-04-09 19:05:30 +00001533 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001534 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1535 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001536
Chris Lattner183b3362004-04-09 19:05:30 +00001537 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1538 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001539 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1540 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001541 }
1542
1543 Value *Op0 = SO, *Op1 = ConstOperand;
1544 if (!ConstIsRHS)
1545 std::swap(Op0, Op1);
1546 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001547 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1548 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1549 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1550 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001551 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001552 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001553 abort();
1554 }
Chris Lattner86102b82005-01-01 16:22:27 +00001555 return IC->InsertNewInstBefore(New, I);
1556}
1557
1558// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1559// constant as the other operand, try to fold the binary operator into the
1560// select arguments. This also works for Cast instructions, which obviously do
1561// not have a second operand.
1562static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1563 InstCombiner *IC) {
1564 // Don't modify shared select instructions
1565 if (!SI->hasOneUse()) return 0;
1566 Value *TV = SI->getOperand(1);
1567 Value *FV = SI->getOperand(2);
1568
1569 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001570 // Bool selects with constant operands can be folded to logical ops.
1571 if (SI->getType() == Type::BoolTy) return 0;
1572
Chris Lattner86102b82005-01-01 16:22:27 +00001573 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1574 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1575
1576 return new SelectInst(SI->getCondition(), SelectTrueVal,
1577 SelectFalseVal);
1578 }
1579 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001580}
1581
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001582
1583/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1584/// node as operand #0, see if we can fold the instruction into the PHI (which
1585/// is only possible if all operands to the PHI are constants).
1586Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1587 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001588 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001589 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001590
Chris Lattner04689872006-09-09 22:02:56 +00001591 // Check to see if all of the operands of the PHI are constants. If there is
1592 // one non-constant value, remember the BB it is. If there is more than one
1593 // bail out.
1594 BasicBlock *NonConstBB = 0;
1595 for (unsigned i = 0; i != NumPHIValues; ++i)
1596 if (!isa<Constant>(PN->getIncomingValue(i))) {
1597 if (NonConstBB) return 0; // More than one non-const value.
1598 NonConstBB = PN->getIncomingBlock(i);
1599
1600 // If the incoming non-constant value is in I's block, we have an infinite
1601 // loop.
1602 if (NonConstBB == I.getParent())
1603 return 0;
1604 }
1605
1606 // If there is exactly one non-constant value, we can insert a copy of the
1607 // operation in that block. However, if this is a critical edge, we would be
1608 // inserting the computation one some other paths (e.g. inside a loop). Only
1609 // do this if the pred block is unconditionally branching into the phi block.
1610 if (NonConstBB) {
1611 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1612 if (!BI || !BI->isUnconditional()) return 0;
1613 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001614
1615 // Okay, we can do the transformation: create the new PHI node.
1616 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1617 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001618 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001619 InsertNewInstBefore(NewPN, *PN);
1620
1621 // Next, add all of the operands to the PHI.
1622 if (I.getNumOperands() == 2) {
1623 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001624 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001625 Value *InV;
1626 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1627 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1628 } else {
1629 assert(PN->getIncomingBlock(i) == NonConstBB);
1630 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1631 InV = BinaryOperator::create(BO->getOpcode(),
1632 PN->getIncomingValue(i), C, "phitmp",
1633 NonConstBB->getTerminator());
1634 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1635 InV = new ShiftInst(SI->getOpcode(),
1636 PN->getIncomingValue(i), C, "phitmp",
1637 NonConstBB->getTerminator());
1638 else
1639 assert(0 && "Unknown binop!");
1640
1641 WorkList.push_back(cast<Instruction>(InV));
1642 }
1643 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001644 }
1645 } else {
1646 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1647 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001648 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001649 Value *InV;
1650 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1651 InV = ConstantExpr::getCast(InC, RetTy);
1652 } else {
1653 assert(PN->getIncomingBlock(i) == NonConstBB);
1654 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1655 NonConstBB->getTerminator());
1656 WorkList.push_back(cast<Instruction>(InV));
1657 }
1658 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001659 }
1660 }
1661 return ReplaceInstUsesWith(I, NewPN);
1662}
1663
Chris Lattner113f4f42002-06-25 16:13:24 +00001664Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001665 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001666 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001667
Chris Lattnercf4a9962004-04-10 22:01:55 +00001668 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001669 // X + undef -> undef
1670 if (isa<UndefValue>(RHS))
1671 return ReplaceInstUsesWith(I, RHS);
1672
Chris Lattnercf4a9962004-04-10 22:01:55 +00001673 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001674 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1675 if (RHSC->isNullValue())
1676 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001677 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1678 if (CFP->isExactlyValue(-0.0))
1679 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001680 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001681
Chris Lattnercf4a9962004-04-10 22:01:55 +00001682 // X + (signbit) --> X ^ signbit
1683 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001684 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001685 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001686 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001687 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001688
1689 if (isa<PHINode>(LHS))
1690 if (Instruction *NV = FoldOpIntoPhi(I))
1691 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001692
Chris Lattner330628a2006-01-06 17:59:59 +00001693 ConstantInt *XorRHS = 0;
1694 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001695 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1696 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1697 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1698 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1699
1700 uint64_t C0080Val = 1ULL << 31;
1701 int64_t CFF80Val = -C0080Val;
1702 unsigned Size = 32;
1703 do {
1704 if (TySizeBits > Size) {
1705 bool Found = false;
1706 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1707 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1708 if (RHSSExt == CFF80Val) {
1709 if (XorRHS->getZExtValue() == C0080Val)
1710 Found = true;
1711 } else if (RHSZExt == C0080Val) {
1712 if (XorRHS->getSExtValue() == CFF80Val)
1713 Found = true;
1714 }
1715 if (Found) {
1716 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001717 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001718 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001719 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001720 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001721 Size = 0; // Not a sign ext, but can't be any others either.
1722 goto FoundSExt;
1723 }
1724 }
1725 Size >>= 1;
1726 C0080Val >>= Size;
1727 CFF80Val >>= Size;
1728 } while (Size >= 8);
1729
1730FoundSExt:
1731 const Type *MiddleType = 0;
1732 switch (Size) {
1733 default: break;
1734 case 32: MiddleType = Type::IntTy; break;
1735 case 16: MiddleType = Type::ShortTy; break;
1736 case 8: MiddleType = Type::SByteTy; break;
1737 }
1738 if (MiddleType) {
1739 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1740 InsertNewInstBefore(NewTrunc, I);
1741 return new CastInst(NewTrunc, I.getType());
1742 }
1743 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001744 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001745
Chris Lattnerb8b97502003-08-13 19:01:45 +00001746 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001747 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001748 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001749
1750 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1751 if (RHSI->getOpcode() == Instruction::Sub)
1752 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1753 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1754 }
1755 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1756 if (LHSI->getOpcode() == Instruction::Sub)
1757 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1758 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1759 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001760 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001761
Chris Lattner147e9752002-05-08 22:46:53 +00001762 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001763 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001764 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001765
1766 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001767 if (!isa<Constant>(RHS))
1768 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001769 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001770
Misha Brukmanb1c93172005-04-21 23:48:37 +00001771
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001772 ConstantInt *C2;
1773 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1774 if (X == RHS) // X*C + X --> X * (C+1)
1775 return BinaryOperator::createMul(RHS, AddOne(C2));
1776
1777 // X*C1 + X*C2 --> X * (C1+C2)
1778 ConstantInt *C1;
1779 if (X == dyn_castFoldableMul(RHS, C1))
1780 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001781 }
1782
1783 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001784 if (dyn_castFoldableMul(RHS, C2) == LHS)
1785 return BinaryOperator::createMul(LHS, AddOne(C2));
1786
Chris Lattner57c8d992003-02-18 19:57:07 +00001787
Chris Lattnerb8b97502003-08-13 19:01:45 +00001788 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001789 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001790 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001791
Chris Lattnerb9cde762003-10-02 15:11:26 +00001792 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001793 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001794 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1795 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1796 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001797 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001798
Chris Lattnerbff91d92004-10-08 05:07:56 +00001799 // (X & FF00) + xx00 -> (X+xx00) & FF00
1800 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1801 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1802 if (Anded == CRHS) {
1803 // See if all bits from the first bit set in the Add RHS up are included
1804 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001805 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001806
1807 // Form a mask of all bits from the lowest bit added through the top.
1808 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001809 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001810
1811 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001812 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001813
Chris Lattnerbff91d92004-10-08 05:07:56 +00001814 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1815 // Okay, the xform is safe. Insert the new add pronto.
1816 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1817 LHS->getName()), I);
1818 return BinaryOperator::createAnd(NewAdd, C2);
1819 }
1820 }
1821 }
1822
Chris Lattnerd4252a72004-07-30 07:50:03 +00001823 // Try to fold constant add into select arguments.
1824 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001825 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001826 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001827 }
1828
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001829 // add (cast *A to intptrtype) B ->
1830 // cast (GEP (cast *A to sbyte*) B) ->
1831 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001832 {
1833 CastInst* CI = dyn_cast<CastInst>(LHS);
1834 Value* Other = RHS;
1835 if (!CI) {
1836 CI = dyn_cast<CastInst>(RHS);
1837 Other = LHS;
1838 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001839 if (CI && CI->getType()->isSized() &&
1840 (CI->getType()->getPrimitiveSize() ==
1841 TD->getIntPtrType()->getPrimitiveSize())
1842 && isa<PointerType>(CI->getOperand(0)->getType())) {
1843 Value* I2 = InsertCastBefore(CI->getOperand(0),
1844 PointerType::get(Type::SByteTy), I);
1845 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1846 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001847 }
1848 }
1849
Chris Lattner113f4f42002-06-25 16:13:24 +00001850 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001851}
1852
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001853// isSignBit - Return true if the value represented by the constant only has the
1854// highest order bit set.
1855static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001856 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001857 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001858}
1859
Chris Lattner022167f2004-03-13 00:11:49 +00001860/// RemoveNoopCast - Strip off nonconverting casts from the value.
1861///
1862static Value *RemoveNoopCast(Value *V) {
1863 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1864 const Type *CTy = CI->getType();
1865 const Type *OpTy = CI->getOperand(0)->getType();
1866 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001867 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001868 return RemoveNoopCast(CI->getOperand(0));
1869 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1870 return RemoveNoopCast(CI->getOperand(0));
1871 }
1872 return V;
1873}
1874
Chris Lattner113f4f42002-06-25 16:13:24 +00001875Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001877
Chris Lattnere6794492002-08-12 21:17:25 +00001878 if (Op0 == Op1) // sub X, X -> 0
1879 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001880
Chris Lattnere6794492002-08-12 21:17:25 +00001881 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001882 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001883 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001884
Chris Lattner81a7a232004-10-16 18:11:37 +00001885 if (isa<UndefValue>(Op0))
1886 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1887 if (isa<UndefValue>(Op1))
1888 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1889
Chris Lattner8f2f5982003-11-05 01:06:05 +00001890 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1891 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001892 if (C->isAllOnesValue())
1893 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001894
Chris Lattner8f2f5982003-11-05 01:06:05 +00001895 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001896 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001897 if (match(Op1, m_Not(m_Value(X))))
1898 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001899 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001900 // -((uint)X >> 31) -> ((int)X >> 31)
1901 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001902 if (C->isNullValue()) {
1903 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1904 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001905 if (SI->getOpcode() == Instruction::Shr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001906 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001907 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001908 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001909 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001910 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001911 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001912 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001913 if (CU->getZExtValue() ==
1914 SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001915 // Ok, the transformation is safe. Insert a cast of the incoming
1916 // value, then the new shift, then the new cast.
1917 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1918 SI->getOperand(0)->getName());
1919 Value *InV = InsertNewInstBefore(FirstCast, I);
1920 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1921 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001922 if (NewShift->getType() == I.getType())
1923 return NewShift;
1924 else {
1925 InV = InsertNewInstBefore(NewShift, I);
1926 return new CastInst(NewShift, I.getType());
1927 }
Chris Lattner92295c52004-03-12 23:53:13 +00001928 }
1929 }
Chris Lattner022167f2004-03-13 00:11:49 +00001930 }
Chris Lattner183b3362004-04-09 19:05:30 +00001931
1932 // Try to fold constant sub into select arguments.
1933 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001934 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001935 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001936
1937 if (isa<PHINode>(Op0))
1938 if (Instruction *NV = FoldOpIntoPhi(I))
1939 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001940 }
1941
Chris Lattnera9be4492005-04-07 16:15:25 +00001942 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1943 if (Op1I->getOpcode() == Instruction::Add &&
1944 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001945 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001946 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001947 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001948 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001949 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1950 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1951 // C1-(X+C2) --> (C1-C2)-X
1952 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1953 Op1I->getOperand(0));
1954 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001955 }
1956
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001957 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001958 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1959 // is not used by anyone else...
1960 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001961 if (Op1I->getOpcode() == Instruction::Sub &&
1962 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001963 // Swap the two operands of the subexpr...
1964 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1965 Op1I->setOperand(0, IIOp1);
1966 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001967
Chris Lattner3082c5a2003-02-18 19:28:33 +00001968 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001969 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001970 }
1971
1972 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1973 //
1974 if (Op1I->getOpcode() == Instruction::And &&
1975 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1976 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1977
Chris Lattner396dbfe2004-06-09 05:08:07 +00001978 Value *NewNot =
1979 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001980 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001981 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001982
Reid Spencer3c514952006-10-16 23:08:08 +00001983 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001984 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001985 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001986 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001987 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001988 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001989 ConstantExpr::getNeg(DivRHS));
1990
Chris Lattner57c8d992003-02-18 19:57:07 +00001991 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001992 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001993 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001994 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001995 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001996 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001997 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001998 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002000
Chris Lattner47060462005-04-07 17:14:51 +00002001 if (!Op0->getType()->isFloatingPoint())
2002 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2003 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002004 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2005 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2006 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2007 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002008 } else if (Op0I->getOpcode() == Instruction::Sub) {
2009 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2010 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002011 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002012
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002013 ConstantInt *C1;
2014 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2015 if (X == Op1) { // X*C - X --> X * (C-1)
2016 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2017 return BinaryOperator::createMul(Op1, CP1);
2018 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002019
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002020 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2021 if (X == dyn_castFoldableMul(Op1, C2))
2022 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2023 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002024 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002025}
2026
Chris Lattnere79e8542004-02-23 06:38:22 +00002027/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2028/// really just returns true if the most significant (sign) bit is set.
2029static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2030 if (RHS->getType()->isSigned()) {
2031 // True if source is LHS < 0 or LHS <= -1
2032 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2033 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2034 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002035 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002036 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2037 // the size of the integer type.
2038 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002039 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002040 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002041 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002042 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002043 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002044 }
2045 return false;
2046}
2047
Chris Lattner113f4f42002-06-25 16:13:24 +00002048Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002049 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002050 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002051
Chris Lattner81a7a232004-10-16 18:11:37 +00002052 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2054
Chris Lattnere6794492002-08-12 21:17:25 +00002055 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002056 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2057 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002058
2059 // ((X << C1)*C2) == (X * (C2 << C1))
2060 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2061 if (SI->getOpcode() == Instruction::Shl)
2062 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002063 return BinaryOperator::createMul(SI->getOperand(0),
2064 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002065
Chris Lattnercce81be2003-09-11 22:24:54 +00002066 if (CI->isNullValue())
2067 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2068 if (CI->equalsInt(1)) // X * 1 == X
2069 return ReplaceInstUsesWith(I, Op0);
2070 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002071 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002072
Reid Spencere0fc4df2006-10-20 07:07:24 +00002073 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002074 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2075 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002076 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002077 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002078 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002079 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002080 if (Op1F->isNullValue())
2081 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002082
Chris Lattner3082c5a2003-02-18 19:28:33 +00002083 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2084 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2085 if (Op1F->getValue() == 1.0)
2086 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2087 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002088
2089 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2090 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2091 isa<ConstantInt>(Op0I->getOperand(1))) {
2092 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2093 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2094 Op1, "tmp");
2095 InsertNewInstBefore(Add, I);
2096 Value *C1C2 = ConstantExpr::getMul(Op1,
2097 cast<Constant>(Op0I->getOperand(1)));
2098 return BinaryOperator::createAdd(Add, C1C2);
2099
2100 }
Chris Lattner183b3362004-04-09 19:05:30 +00002101
2102 // Try to fold constant mul into select arguments.
2103 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002104 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002105 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002106
2107 if (isa<PHINode>(Op0))
2108 if (Instruction *NV = FoldOpIntoPhi(I))
2109 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002110 }
2111
Chris Lattner934a64cf2003-03-10 23:23:04 +00002112 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2113 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002114 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002115
Chris Lattner2635b522004-02-23 05:39:21 +00002116 // If one of the operands of the multiply is a cast from a boolean value, then
2117 // we know the bool is either zero or one, so this is a 'masking' multiply.
2118 // See if we can simplify things based on how the boolean was originally
2119 // formed.
2120 CastInst *BoolCast = 0;
2121 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2122 if (CI->getOperand(0)->getType() == Type::BoolTy)
2123 BoolCast = CI;
2124 if (!BoolCast)
2125 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2126 if (CI->getOperand(0)->getType() == Type::BoolTy)
2127 BoolCast = CI;
2128 if (BoolCast) {
2129 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2130 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2131 const Type *SCOpTy = SCIOp0->getType();
2132
Chris Lattnere79e8542004-02-23 06:38:22 +00002133 // If the setcc is true iff the sign bit of X is set, then convert this
2134 // multiply into a shift/and combination.
2135 if (isa<ConstantInt>(SCIOp1) &&
2136 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002137 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002138 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002139 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002140 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002141 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00002142 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
2143 SCIOp0->getName()), I);
2144 }
2145
2146 Value *V =
2147 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2148 BoolCast->getOperand(0)->getName()+
2149 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002150
2151 // If the multiply type is not the same as the source type, sign extend
2152 // or truncate to the multiply type.
2153 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00002154 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002155
Chris Lattner2635b522004-02-23 05:39:21 +00002156 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002157 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002158 }
2159 }
2160 }
2161
Chris Lattner113f4f42002-06-25 16:13:24 +00002162 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002163}
2164
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002165/// This function implements the transforms on div instructions that work
2166/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2167/// used by the visitors to those instructions.
2168/// @brief Transforms common to all three div instructions
2169Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002171
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002172 // undef / X -> 0
2173 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002174 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002175
2176 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002177 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002178 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002179
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002180 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002181 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2182 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002183 // same basic block, then we replace the select with Y, and the condition
2184 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002185 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002186 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002187 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2188 if (ST->isNullValue()) {
2189 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2190 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002191 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002192 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2193 I.setOperand(1, SI->getOperand(2));
2194 else
2195 UpdateValueUsesWith(SI, SI->getOperand(2));
2196 return &I;
2197 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002198
Chris Lattnerd79dc792006-09-09 20:26:32 +00002199 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2200 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2201 if (ST->isNullValue()) {
2202 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2203 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002204 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002205 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2206 I.setOperand(1, SI->getOperand(1));
2207 else
2208 UpdateValueUsesWith(SI, SI->getOperand(1));
2209 return &I;
2210 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002211 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002212
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002213 return 0;
2214}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002215
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002216/// This function implements the transforms common to both integer division
2217/// instructions (udiv and sdiv). It is called by the visitors to those integer
2218/// division instructions.
2219/// @brief Common integer divide transforms
2220Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2222
2223 if (Instruction *Common = commonDivTransforms(I))
2224 return Common;
2225
2226 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2227 // div X, 1 == X
2228 if (RHS->equalsInt(1))
2229 return ReplaceInstUsesWith(I, Op0);
2230
2231 // (X / C1) / C2 -> X / (C1*C2)
2232 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2233 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2234 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2235 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2236 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002237 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002238
2239 if (!RHS->isNullValue()) { // avoid X udiv 0
2240 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2241 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2242 return R;
2243 if (isa<PHINode>(Op0))
2244 if (Instruction *NV = FoldOpIntoPhi(I))
2245 return NV;
2246 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002247 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002248
Chris Lattner3082c5a2003-02-18 19:28:33 +00002249 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002250 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002251 if (LHS->equalsInt(0))
2252 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2253
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002254 return 0;
2255}
2256
2257Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2259
2260 // Handle the integer div common cases
2261 if (Instruction *Common = commonIDivTransforms(I))
2262 return Common;
2263
2264 // X udiv C^2 -> X >> C
2265 // Check to see if this is an unsigned division with an exact power of 2,
2266 // if so, convert to a right shift.
2267 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2268 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2269 if (isPowerOf2_64(Val)) {
2270 uint64_t ShiftAmt = Log2_64(Val);
2271 Value* X = Op0;
2272 const Type* XTy = X->getType();
2273 bool isSigned = XTy->isSigned();
2274 if (isSigned)
2275 X = InsertCastBefore(X, XTy->getUnsignedVersion(), I);
2276 Instruction* Result =
2277 new ShiftInst(Instruction::Shr, X,
2278 ConstantInt::get(Type::UByteTy, ShiftAmt));
2279 if (!isSigned)
2280 return Result;
2281 InsertNewInstBefore(Result, I);
2282 return new CastInst(Result, XTy->getSignedVersion(), I.getName());
2283 }
2284 }
2285
2286 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2287 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2288 if (RHSI->getOpcode() == Instruction::Shl &&
2289 isa<ConstantInt>(RHSI->getOperand(0))) {
2290 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2291 if (isPowerOf2_64(C1)) {
2292 Value *N = RHSI->getOperand(1);
2293 const Type* NTy = N->getType();
2294 bool isSigned = NTy->isSigned();
2295 if (uint64_t C2 = Log2_64(C1)) {
2296 if (isSigned) {
2297 NTy = NTy->getUnsignedVersion();
2298 N = InsertCastBefore(N, NTy, I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002299 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002300 Constant *C2V = ConstantInt::get(NTy, C2);
2301 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002302 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002303 Instruction* Result = new ShiftInst(Instruction::Shr, Op0, N);
2304 if (!isSigned)
2305 return Result;
2306 InsertNewInstBefore(Result, I);
2307 return new CastInst(Result, NTy->getSignedVersion(), I.getName());
Chris Lattner2e90b732006-02-05 07:54:04 +00002308 }
2309 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002310 }
2311
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002312 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2313 // where C1&C2 are powers of two.
2314 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2315 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2316 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2317 if (!STO->isNullValue() && !STO->isNullValue()) {
2318 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2319 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2320 // Compute the shift amounts
2321 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2322 // Make sure we get the unsigned version of X
2323 Value* X = Op0;
2324 const Type* origXTy = X->getType();
2325 bool isSigned = origXTy->isSigned();
2326 if (isSigned)
2327 X = InsertCastBefore(X, X->getType()->getUnsignedVersion(), I);
2328 // Construct the "on true" case of the select
2329 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2330 Instruction *TSI =
2331 new ShiftInst(Instruction::Shr, X, TC, SI->getName()+".t");
2332 TSI = InsertNewInstBefore(TSI, I);
2333
2334 // Construct the "on false" case of the select
2335 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2336 Instruction *FSI =
2337 new ShiftInst(Instruction::Shr, X, FC, SI->getName()+".f");
2338 FSI = InsertNewInstBefore(FSI, I);
2339
2340 // construct the select instruction and return it.
2341 SelectInst* NewSI =
2342 new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2343 if (!isSigned)
2344 return NewSI;
2345 InsertNewInstBefore(NewSI, I);
2346 return new CastInst(NewSI, origXTy, NewSI->getName());
2347 }
2348 }
2349 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002350 return 0;
2351}
2352
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002353Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2354 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2355
2356 // Handle the integer div common cases
2357 if (Instruction *Common = commonIDivTransforms(I))
2358 return Common;
2359
2360 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2361 // sdiv X, -1 == -X
2362 if (RHS->isAllOnesValue())
2363 return BinaryOperator::createNeg(Op0);
2364
2365 // -X/C -> X/-C
2366 if (Value *LHSNeg = dyn_castNegVal(Op0))
2367 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2368 }
2369
2370 // If the sign bits of both operands are zero (i.e. we can prove they are
2371 // unsigned inputs), turn this into a udiv.
2372 if (I.getType()->isInteger()) {
2373 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2374 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2375 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2376 }
2377 }
2378
2379 return 0;
2380}
2381
2382Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2383 return commonDivTransforms(I);
2384}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002385
Chris Lattner85dda9a2006-03-02 06:50:58 +00002386/// GetFactor - If we can prove that the specified value is at least a multiple
2387/// of some factor, return that factor.
2388static Constant *GetFactor(Value *V) {
2389 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2390 return CI;
2391
2392 // Unless we can be tricky, we know this is a multiple of 1.
2393 Constant *Result = ConstantInt::get(V->getType(), 1);
2394
2395 Instruction *I = dyn_cast<Instruction>(V);
2396 if (!I) return Result;
2397
2398 if (I->getOpcode() == Instruction::Mul) {
2399 // Handle multiplies by a constant, etc.
2400 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2401 GetFactor(I->getOperand(1)));
2402 } else if (I->getOpcode() == Instruction::Shl) {
2403 // (X<<C) -> X * (1 << C)
2404 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2405 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2406 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2407 }
2408 } else if (I->getOpcode() == Instruction::And) {
2409 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2410 // X & 0xFFF0 is known to be a multiple of 16.
2411 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2412 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2413 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002414 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002415 }
2416 } else if (I->getOpcode() == Instruction::Cast) {
2417 Value *Op = I->getOperand(0);
2418 // Only handle int->int casts.
2419 if (!Op->getType()->isInteger()) return Result;
2420 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2421 }
2422 return Result;
2423}
2424
Chris Lattner113f4f42002-06-25 16:13:24 +00002425Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002427
2428 // 0 % X == 0, we don't need to preserve faults!
2429 if (Constant *LHS = dyn_cast<Constant>(Op0))
2430 if (LHS->isNullValue())
2431 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2432
2433 if (isa<UndefValue>(Op0)) // undef % X -> 0
2434 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2435 if (isa<UndefValue>(Op1))
2436 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2437
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002438 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002439 if (Value *RHSNeg = dyn_castNegVal(Op1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00002440 if (!isa<ConstantInt>(RHSNeg) || !RHSNeg->getType()->isSigned() ||
2441 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002442 // X % -Y -> X % Y
2443 AddUsesToWorkList(I);
2444 I.setOperand(1, RHSNeg);
2445 return &I;
2446 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002447
2448 // If the top bits of both operands are zero (i.e. we can prove they are
2449 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002450 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2451 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002452 const Type *NTy = Op0->getType()->getUnsignedVersion();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002453 Value *LHS = InsertCastBefore(Op0, NTy, I);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002454 Value *RHS;
2455 if (Constant *R = dyn_cast<Constant>(Op1))
2456 RHS = ConstantExpr::getCast(R, NTy);
2457 else
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002458 RHS = InsertCastBefore(Op1, NTy, I);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002459 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2460 InsertNewInstBefore(Rem, I);
2461 return new CastInst(Rem, I.getType());
2462 }
2463 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002464
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002465 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002466 // X % 0 == undef, we don't need to preserve faults!
2467 if (RHS->equalsInt(0))
2468 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2469
Chris Lattner3082c5a2003-02-18 19:28:33 +00002470 if (RHS->equalsInt(1)) // X % 1 == 0
2471 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2472
2473 // Check to see if this is an unsigned remainder with an exact power of 2,
2474 // if so, convert to a bitwise and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002475 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2476 if (RHS->getType()->isUnsigned())
2477 if (isPowerOf2_64(C->getZExtValue()))
2478 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002479
Chris Lattnerb70f1412006-02-28 05:49:21 +00002480 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2483 return R;
2484 } else if (isa<PHINode>(Op0I)) {
2485 if (Instruction *NV = FoldOpIntoPhi(I))
2486 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002487 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002488
2489 // X*C1%C2 --> 0 iff C1%C2 == 0
2490 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2491 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002492 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002493 }
2494
Chris Lattner2e90b732006-02-05 07:54:04 +00002495 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2496 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2497 if (I.getType()->isUnsigned() &&
2498 RHSI->getOpcode() == Instruction::Shl &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00002499 isa<ConstantInt>(RHSI->getOperand(0)) &&
2500 RHSI->getOperand(0)->getType()->isUnsigned()) {
2501 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002502 if (isPowerOf2_64(C1)) {
2503 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2504 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2505 "tmp"), I);
2506 return BinaryOperator::createAnd(Op0, Add);
2507 }
2508 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002509
2510 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2511 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002512 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2513 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2514 // the same basic block, then we replace the select with Y, and the
2515 // condition of the select with false (if the cond value is in the same
2516 // BB). If the select has uses other than the div, this allows them to be
2517 // simplified also.
2518 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2519 if (ST->isNullValue()) {
2520 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2521 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002522 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002523 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2524 I.setOperand(1, SI->getOperand(2));
2525 else
2526 UpdateValueUsesWith(SI, SI->getOperand(2));
2527 return &I;
2528 }
2529 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2530 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2531 if (ST->isNullValue()) {
2532 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2533 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002534 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002535 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2536 I.setOperand(1, SI->getOperand(1));
2537 else
2538 UpdateValueUsesWith(SI, SI->getOperand(1));
2539 return &I;
2540 }
2541
2542
Reid Spencere0fc4df2006-10-20 07:07:24 +00002543 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2544 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2545 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2546 // STO == 0 and SFO == 0 handled above.
2547 if (isPowerOf2_64(STO->getZExtValue()) &&
2548 isPowerOf2_64(SFO->getZExtValue())) {
2549 Value *TrueAnd = InsertNewInstBefore(
2550 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"),
2551 I);
2552 Value *FalseAnd = InsertNewInstBefore(
2553 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"),
2554 I);
2555 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2556 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002557 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002558 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002559 }
2560
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002561 return 0;
2562}
2563
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002564// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002565static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002566 if (C->getType()->isUnsigned())
2567 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002568
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002569 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002570 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002571 int64_t Val = INT64_MAX; // All ones
2572 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002573 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002574}
2575
2576// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002577static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002578 if (C->getType()->isUnsigned())
2579 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002580
2581 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002582 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002583 int64_t Val = -1; // All ones
2584 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002585 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002586}
2587
Chris Lattner35167c32004-06-09 07:59:58 +00002588// isOneBitSet - Return true if there is exactly one bit set in the specified
2589// constant.
2590static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002591 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002592 return V && (V & (V-1)) == 0;
2593}
2594
Chris Lattner8fc5af42004-09-23 21:46:38 +00002595#if 0 // Currently unused
2596// isLowOnes - Return true if the constant is of the form 0+1+.
2597static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002598 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002599
2600 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002601 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002602
2603 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2604 return U && V && (U & V) == 0;
2605}
2606#endif
2607
2608// isHighOnes - Return true if the constant is of the form 1+0+.
2609// This is the same as lowones(~X).
2610static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002611 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002612 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002613
2614 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002615 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002616
2617 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2618 return U && V && (U & V) == 0;
2619}
2620
2621
Chris Lattner3ac7c262003-08-13 20:16:26 +00002622/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2623/// are carefully arranged to allow folding of expressions such as:
2624///
2625/// (A < B) | (A > B) --> (A != B)
2626///
2627/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2628/// represents that the comparison is true if A == B, and bit value '1' is true
2629/// if A < B.
2630///
2631static unsigned getSetCondCode(const SetCondInst *SCI) {
2632 switch (SCI->getOpcode()) {
2633 // False -> 0
2634 case Instruction::SetGT: return 1;
2635 case Instruction::SetEQ: return 2;
2636 case Instruction::SetGE: return 3;
2637 case Instruction::SetLT: return 4;
2638 case Instruction::SetNE: return 5;
2639 case Instruction::SetLE: return 6;
2640 // True -> 7
2641 default:
2642 assert(0 && "Invalid SetCC opcode!");
2643 return 0;
2644 }
2645}
2646
2647/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2648/// opcode and two operands into either a constant true or false, or a brand new
2649/// SetCC instruction.
2650static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2651 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002652 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002653 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2654 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2655 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2656 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2657 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2658 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002659 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002660 default: assert(0 && "Illegal SetCCCode!"); return 0;
2661 }
2662}
2663
2664// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2665struct FoldSetCCLogical {
2666 InstCombiner &IC;
2667 Value *LHS, *RHS;
2668 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2669 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2670 bool shouldApply(Value *V) const {
2671 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2672 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2673 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2674 return false;
2675 }
2676 Instruction *apply(BinaryOperator &Log) const {
2677 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2678 if (SCI->getOperand(0) != LHS) {
2679 assert(SCI->getOperand(1) == LHS);
2680 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2681 }
2682
2683 unsigned LHSCode = getSetCondCode(SCI);
2684 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2685 unsigned Code;
2686 switch (Log.getOpcode()) {
2687 case Instruction::And: Code = LHSCode & RHSCode; break;
2688 case Instruction::Or: Code = LHSCode | RHSCode; break;
2689 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002690 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002691 }
2692
2693 Value *RV = getSetCCValue(Code, LHS, RHS);
2694 if (Instruction *I = dyn_cast<Instruction>(RV))
2695 return I;
2696 // Otherwise, it's a constant boolean value...
2697 return IC.ReplaceInstUsesWith(Log, RV);
2698 }
2699};
2700
Chris Lattnerba1cb382003-09-19 17:17:26 +00002701// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2702// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2703// guaranteed to be either a shift instruction or a binary operator.
2704Instruction *InstCombiner::OptAndOp(Instruction *Op,
2705 ConstantIntegral *OpRHS,
2706 ConstantIntegral *AndRHS,
2707 BinaryOperator &TheAnd) {
2708 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002709 Constant *Together = 0;
2710 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002711 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002712
Chris Lattnerba1cb382003-09-19 17:17:26 +00002713 switch (Op->getOpcode()) {
2714 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002715 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002716 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2717 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002718 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002719 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002720 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002721 }
2722 break;
2723 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002724 if (Together == AndRHS) // (X | C) & C --> C
2725 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002726
Chris Lattner86102b82005-01-01 16:22:27 +00002727 if (Op->hasOneUse() && Together != OpRHS) {
2728 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2729 std::string Op0Name = Op->getName(); Op->setName("");
2730 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2731 InsertNewInstBefore(Or, TheAnd);
2732 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002733 }
2734 break;
2735 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002736 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002737 // Adding a one to a single bit bit-field should be turned into an XOR
2738 // of the bit. First thing to check is to see if this AND is with a
2739 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002740 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002741
2742 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002743 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002744
2745 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002746 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002747 // Ok, at this point, we know that we are masking the result of the
2748 // ADD down to exactly one bit. If the constant we are adding has
2749 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002750 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002751
Chris Lattnerba1cb382003-09-19 17:17:26 +00002752 // Check to see if any bits below the one bit set in AndRHSV are set.
2753 if ((AddRHS & (AndRHSV-1)) == 0) {
2754 // If not, the only thing that can effect the output of the AND is
2755 // the bit specified by AndRHSV. If that bit is set, the effect of
2756 // the XOR is to toggle the bit. If it is clear, then the ADD has
2757 // no effect.
2758 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2759 TheAnd.setOperand(0, X);
2760 return &TheAnd;
2761 } else {
2762 std::string Name = Op->getName(); Op->setName("");
2763 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002764 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002765 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002766 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002767 }
2768 }
2769 }
2770 }
2771 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002772
2773 case Instruction::Shl: {
2774 // We know that the AND will not produce any of the bits shifted in, so if
2775 // the anded constant includes them, clear them now!
2776 //
2777 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002778 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2779 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002780
Chris Lattner7e794272004-09-24 15:21:34 +00002781 if (CI == ShlMask) { // Masking out bits that the shift already masks
2782 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2783 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002784 TheAnd.setOperand(1, CI);
2785 return &TheAnd;
2786 }
2787 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002788 }
Chris Lattner2da29172003-09-19 19:05:02 +00002789 case Instruction::Shr:
2790 // 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 //
2794 if (AndRHS->getType()->isUnsigned()) {
2795 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002796 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2797 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2798
2799 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2800 return ReplaceInstUsesWith(TheAnd, Op);
2801 } else if (CI != AndRHS) {
2802 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002803 return &TheAnd;
2804 }
Chris Lattner7e794272004-09-24 15:21:34 +00002805 } else { // Signed shr.
2806 // See if this is shifting in some sign extension, then masking it out
2807 // with an and.
2808 if (Op->hasOneUse()) {
2809 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2810 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2811 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002812 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002813 // Make the argument unsigned.
2814 Value *ShVal = Op->getOperand(0);
2815 ShVal = InsertCastBefore(ShVal,
2816 ShVal->getType()->getUnsignedVersion(),
2817 TheAnd);
2818 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2819 OpRHS, Op->getName()),
2820 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002821 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2822 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2823 TheAnd.getName()),
2824 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002825 return new CastInst(ShVal, Op->getType());
2826 }
2827 }
Chris Lattner2da29172003-09-19 19:05:02 +00002828 }
2829 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002830 }
2831 return 0;
2832}
2833
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002834
Chris Lattner6862fbd2004-09-29 17:40:11 +00002835/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2836/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2837/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2838/// insert new instructions.
2839Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2840 bool Inside, Instruction &IB) {
2841 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2842 "Lo is not <= Hi in range emission code!");
2843 if (Inside) {
2844 if (Lo == Hi) // Trivially false.
2845 return new SetCondInst(Instruction::SetNE, V, V);
2846 if (cast<ConstantIntegral>(Lo)->isMinValue())
2847 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002848
Chris Lattner6862fbd2004-09-29 17:40:11 +00002849 Constant *AddCST = ConstantExpr::getNeg(Lo);
2850 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2851 InsertNewInstBefore(Add, IB);
2852 // Convert to unsigned for the comparison.
2853 const Type *UnsType = Add->getType()->getUnsignedVersion();
2854 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2855 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2856 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2857 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2858 }
2859
2860 if (Lo == Hi) // Trivially true.
2861 return new SetCondInst(Instruction::SetEQ, V, V);
2862
2863 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002864
2865 // V < 0 || V >= Hi ->'V > Hi-1'
2866 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002867 return new SetCondInst(Instruction::SetGT, V, Hi);
2868
2869 // Emit X-Lo > Hi-Lo-1
2870 Constant *AddCST = ConstantExpr::getNeg(Lo);
2871 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2872 InsertNewInstBefore(Add, IB);
2873 // Convert to unsigned for the comparison.
2874 const Type *UnsType = Add->getType()->getUnsignedVersion();
2875 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2876 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2877 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2878 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2879}
2880
Chris Lattnerb4b25302005-09-18 07:22:02 +00002881// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2882// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2883// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2884// not, since all 1s are not contiguous.
2885static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002886 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002887 if (!isShiftedMask_64(V)) return false;
2888
2889 // look for the first zero bit after the run of ones
2890 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2891 // look for the first non-zero bit
2892 ME = 64-CountLeadingZeros_64(V);
2893 return true;
2894}
2895
2896
2897
2898/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2899/// where isSub determines whether the operator is a sub. If we can fold one of
2900/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002901///
2902/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2903/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2904/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2905///
2906/// return (A +/- B).
2907///
2908Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2909 ConstantIntegral *Mask, bool isSub,
2910 Instruction &I) {
2911 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2912 if (!LHSI || LHSI->getNumOperands() != 2 ||
2913 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2914
2915 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2916
2917 switch (LHSI->getOpcode()) {
2918 default: return 0;
2919 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002920 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2921 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002922 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002923 break;
2924
2925 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2926 // part, we don't need any explicit masks to take them out of A. If that
2927 // is all N is, ignore it.
2928 unsigned MB, ME;
2929 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002930 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2931 Mask >>= 64-MB+1;
2932 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002933 break;
2934 }
2935 }
Chris Lattneraf517572005-09-18 04:24:45 +00002936 return 0;
2937 case Instruction::Or:
2938 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002939 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002940 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002941 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002942 break;
2943 return 0;
2944 }
2945
2946 Instruction *New;
2947 if (isSub)
2948 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2949 else
2950 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2951 return InsertNewInstBefore(New, I);
2952}
2953
Chris Lattner113f4f42002-06-25 16:13:24 +00002954Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002955 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002956 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002957
Chris Lattner81a7a232004-10-16 18:11:37 +00002958 if (isa<UndefValue>(Op1)) // X & undef -> 0
2959 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2960
Chris Lattner86102b82005-01-01 16:22:27 +00002961 // and X, X = X
2962 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002963 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002964
Chris Lattner5b2edb12006-02-12 08:02:11 +00002965 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002966 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002967 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002968 if (!isa<PackedType>(I.getType()) &&
2969 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002970 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002971 return &I;
2972
Chris Lattner86102b82005-01-01 16:22:27 +00002973 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002974 uint64_t AndRHSMask = AndRHS->getZExtValue();
2975 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002976 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002977
Chris Lattnerba1cb382003-09-19 17:17:26 +00002978 // Optimize a variety of ((val OP C1) & C2) combinations...
2979 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2980 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002981 Value *Op0LHS = Op0I->getOperand(0);
2982 Value *Op0RHS = Op0I->getOperand(1);
2983 switch (Op0I->getOpcode()) {
2984 case Instruction::Xor:
2985 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002986 // If the mask is only needed on one incoming arm, push it up.
2987 if (Op0I->hasOneUse()) {
2988 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2989 // Not masking anything out for the LHS, move to RHS.
2990 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2991 Op0RHS->getName()+".masked");
2992 InsertNewInstBefore(NewRHS, I);
2993 return BinaryOperator::create(
2994 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002995 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002996 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002997 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2998 // Not masking anything out for the RHS, move to LHS.
2999 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3000 Op0LHS->getName()+".masked");
3001 InsertNewInstBefore(NewLHS, I);
3002 return BinaryOperator::create(
3003 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3004 }
3005 }
3006
Chris Lattner86102b82005-01-01 16:22:27 +00003007 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003008 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003009 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3010 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3011 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3012 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3013 return BinaryOperator::createAnd(V, AndRHS);
3014 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3015 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003016 break;
3017
3018 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003019 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3020 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3021 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3022 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3023 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003024 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003025 }
3026
Chris Lattner16464b32003-07-23 19:25:52 +00003027 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003028 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003029 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003030 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3031 const Type *SrcTy = CI->getOperand(0)->getType();
3032
Chris Lattner2c14cf72005-08-07 07:03:10 +00003033 // If this is an integer truncation or change from signed-to-unsigned, and
3034 // if the source is an and/or with immediate, transform it. This
3035 // frequently occurs for bitfield accesses.
3036 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3037 if (SrcTy->getPrimitiveSizeInBits() >=
3038 I.getType()->getPrimitiveSizeInBits() &&
3039 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003040 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003041 if (CastOp->getOpcode() == Instruction::And) {
3042 // Change: and (cast (and X, C1) to T), C2
3043 // into : and (cast X to T), trunc(C1)&C2
3044 // This will folds the two ands together, which may allow other
3045 // simplifications.
3046 Instruction *NewCast =
3047 new CastInst(CastOp->getOperand(0), I.getType(),
3048 CastOp->getName()+".shrunk");
3049 NewCast = InsertNewInstBefore(NewCast, I);
3050
3051 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3052 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3053 return BinaryOperator::createAnd(NewCast, C3);
3054 } else if (CastOp->getOpcode() == Instruction::Or) {
3055 // Change: and (cast (or X, C1) to T), C2
3056 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3057 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3058 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3059 return ReplaceInstUsesWith(I, AndRHS);
3060 }
3061 }
Chris Lattner33217db2003-07-23 19:36:21 +00003062 }
Chris Lattner183b3362004-04-09 19:05:30 +00003063
3064 // Try to fold constant and into select arguments.
3065 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003066 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003067 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003068 if (isa<PHINode>(Op0))
3069 if (Instruction *NV = FoldOpIntoPhi(I))
3070 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003071 }
3072
Chris Lattnerbb74e222003-03-10 23:06:50 +00003073 Value *Op0NotVal = dyn_castNotVal(Op0);
3074 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003075
Chris Lattner023a4832004-06-18 06:07:51 +00003076 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3077 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3078
Misha Brukman9c003d82004-07-30 12:50:08 +00003079 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003080 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003081 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3082 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003083 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003084 return BinaryOperator::createNot(Or);
3085 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003086
3087 {
3088 Value *A = 0, *B = 0;
3089 ConstantInt *C1 = 0, *C2 = 0;
3090 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3091 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3092 return ReplaceInstUsesWith(I, Op1);
3093 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3094 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3095 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003096
3097 if (Op0->hasOneUse() &&
3098 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3099 if (A == Op1) { // (A^B)&A -> A&(A^B)
3100 I.swapOperands(); // Simplify below
3101 std::swap(Op0, Op1);
3102 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3103 cast<BinaryOperator>(Op0)->swapOperands();
3104 I.swapOperands(); // Simplify below
3105 std::swap(Op0, Op1);
3106 }
3107 }
3108 if (Op1->hasOneUse() &&
3109 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3110 if (B == Op0) { // B&(A^B) -> B&(B^A)
3111 cast<BinaryOperator>(Op1)->swapOperands();
3112 std::swap(A, B);
3113 }
3114 if (A == Op0) { // A&(A^B) -> A & ~B
3115 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3116 InsertNewInstBefore(NotB, I);
3117 return BinaryOperator::createAnd(A, NotB);
3118 }
3119 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003120 }
3121
Chris Lattner3082c5a2003-02-18 19:28:33 +00003122
Chris Lattner623826c2004-09-28 21:48:02 +00003123 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3124 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003125 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3126 return R;
3127
Chris Lattner623826c2004-09-28 21:48:02 +00003128 Value *LHSVal, *RHSVal;
3129 ConstantInt *LHSCst, *RHSCst;
3130 Instruction::BinaryOps LHSCC, RHSCC;
3131 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3132 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3133 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3134 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003135 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003136 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3137 // Ensure that the larger constant is on the RHS.
3138 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3139 SetCondInst *LHS = cast<SetCondInst>(Op0);
3140 if (cast<ConstantBool>(Cmp)->getValue()) {
3141 std::swap(LHS, RHS);
3142 std::swap(LHSCst, RHSCst);
3143 std::swap(LHSCC, RHSCC);
3144 }
3145
3146 // At this point, we know we have have two setcc instructions
3147 // comparing a value against two constants and and'ing the result
3148 // together. Because of the above check, we know that we only have
3149 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3150 // FoldSetCCLogical check above), that the two constants are not
3151 // equal.
3152 assert(LHSCst != RHSCst && "Compares not folded above?");
3153
3154 switch (LHSCC) {
3155 default: assert(0 && "Unknown integer condition code!");
3156 case Instruction::SetEQ:
3157 switch (RHSCC) {
3158 default: assert(0 && "Unknown integer condition code!");
3159 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3160 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003161 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003162 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3163 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3164 return ReplaceInstUsesWith(I, LHS);
3165 }
3166 case Instruction::SetNE:
3167 switch (RHSCC) {
3168 default: assert(0 && "Unknown integer condition code!");
3169 case Instruction::SetLT:
3170 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3171 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3172 break; // (X != 13 & X < 15) -> no change
3173 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3174 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3175 return ReplaceInstUsesWith(I, RHS);
3176 case Instruction::SetNE:
3177 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3178 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3179 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3180 LHSVal->getName()+".off");
3181 InsertNewInstBefore(Add, I);
3182 const Type *UnsType = Add->getType()->getUnsignedVersion();
3183 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3184 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3185 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3186 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3187 }
3188 break; // (X != 13 & X != 15) -> no change
3189 }
3190 break;
3191 case Instruction::SetLT:
3192 switch (RHSCC) {
3193 default: assert(0 && "Unknown integer condition code!");
3194 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3195 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003196 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003197 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3198 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3199 return ReplaceInstUsesWith(I, LHS);
3200 }
3201 case Instruction::SetGT:
3202 switch (RHSCC) {
3203 default: assert(0 && "Unknown integer condition code!");
3204 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3205 return ReplaceInstUsesWith(I, LHS);
3206 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3207 return ReplaceInstUsesWith(I, RHS);
3208 case Instruction::SetNE:
3209 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3210 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3211 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003212 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3213 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003214 }
3215 }
3216 }
3217 }
3218
Chris Lattner3af10532006-05-05 06:39:07 +00003219 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3220 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003221 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003222 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003223 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003224 // Only do this if the casts both really cause code to be generated.
3225 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3226 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003227 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3228 Op1C->getOperand(0),
3229 I.getName());
3230 InsertNewInstBefore(NewOp, I);
3231 return new CastInst(NewOp, I.getType());
3232 }
3233 }
3234
Chris Lattner113f4f42002-06-25 16:13:24 +00003235 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003236}
3237
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003238/// CollectBSwapParts - Look to see if the specified value defines a single byte
3239/// in the result. If it does, and if the specified byte hasn't been filled in
3240/// yet, fill it in and return false.
3241static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3242 Instruction *I = dyn_cast<Instruction>(V);
3243 if (I == 0) return true;
3244
3245 // If this is an or instruction, it is an inner node of the bswap.
3246 if (I->getOpcode() == Instruction::Or)
3247 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3248 CollectBSwapParts(I->getOperand(1), ByteValues);
3249
3250 // If this is a shift by a constant int, and it is "24", then its operand
3251 // defines a byte. We only handle unsigned types here.
3252 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3253 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003254 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003255 8*(ByteValues.size()-1))
3256 return true;
3257
3258 unsigned DestNo;
3259 if (I->getOpcode() == Instruction::Shl) {
3260 // X << 24 defines the top byte with the lowest of the input bytes.
3261 DestNo = ByteValues.size()-1;
3262 } else {
3263 // X >>u 24 defines the low byte with the highest of the input bytes.
3264 DestNo = 0;
3265 }
3266
3267 // If the destination byte value is already defined, the values are or'd
3268 // together, which isn't a bswap (unless it's an or of the same bits).
3269 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3270 return true;
3271 ByteValues[DestNo] = I->getOperand(0);
3272 return false;
3273 }
3274
3275 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3276 // don't have this.
3277 Value *Shift = 0, *ShiftLHS = 0;
3278 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3279 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3280 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3281 return true;
3282 Instruction *SI = cast<Instruction>(Shift);
3283
3284 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003285 if (ShiftAmt->getZExtValue() & 7 ||
3286 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003287 return true;
3288
3289 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3290 unsigned DestByte;
3291 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003292 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003293 break;
3294 // Unknown mask for bswap.
3295 if (DestByte == ByteValues.size()) return true;
3296
Reid Spencere0fc4df2006-10-20 07:07:24 +00003297 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003298 unsigned SrcByte;
3299 if (SI->getOpcode() == Instruction::Shl)
3300 SrcByte = DestByte - ShiftBytes;
3301 else
3302 SrcByte = DestByte + ShiftBytes;
3303
3304 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3305 if (SrcByte != ByteValues.size()-DestByte-1)
3306 return true;
3307
3308 // If the destination byte value is already defined, the values are or'd
3309 // together, which isn't a bswap (unless it's an or of the same bits).
3310 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3311 return true;
3312 ByteValues[DestByte] = SI->getOperand(0);
3313 return false;
3314}
3315
3316/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3317/// If so, insert the new bswap intrinsic and return it.
3318Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3319 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3320 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3321 return 0;
3322
3323 /// ByteValues - For each byte of the result, we keep track of which value
3324 /// defines each byte.
3325 std::vector<Value*> ByteValues;
3326 ByteValues.resize(I.getType()->getPrimitiveSize());
3327
3328 // Try to find all the pieces corresponding to the bswap.
3329 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3330 CollectBSwapParts(I.getOperand(1), ByteValues))
3331 return 0;
3332
3333 // Check to see if all of the bytes come from the same value.
3334 Value *V = ByteValues[0];
3335 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3336
3337 // Check to make sure that all of the bytes come from the same value.
3338 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3339 if (ByteValues[i] != V)
3340 return 0;
3341
3342 // If they do then *success* we can turn this into a bswap. Figure out what
3343 // bswap to make it into.
3344 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003345 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003346 if (I.getType() == Type::UShortTy)
3347 FnName = "llvm.bswap.i16";
3348 else if (I.getType() == Type::UIntTy)
3349 FnName = "llvm.bswap.i32";
3350 else if (I.getType() == Type::ULongTy)
3351 FnName = "llvm.bswap.i64";
3352 else
3353 assert(0 && "Unknown integer type!");
3354 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3355
3356 return new CallInst(F, V);
3357}
3358
3359
Chris Lattner113f4f42002-06-25 16:13:24 +00003360Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003361 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003362 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003363
Chris Lattner81a7a232004-10-16 18:11:37 +00003364 if (isa<UndefValue>(Op1))
3365 return ReplaceInstUsesWith(I, // X | undef -> -1
3366 ConstantIntegral::getAllOnesValue(I.getType()));
3367
Chris Lattner5b2edb12006-02-12 08:02:11 +00003368 // or X, X = X
3369 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003370 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003371
Chris Lattner5b2edb12006-02-12 08:02:11 +00003372 // See if we can simplify any instructions used by the instruction whose sole
3373 // purpose is to compute bits we don't care about.
3374 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003375 if (!isa<PackedType>(I.getType()) &&
3376 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003377 KnownZero, KnownOne))
3378 return &I;
3379
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003380 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003381 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003382 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003383 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3384 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003385 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3386 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003387 InsertNewInstBefore(Or, I);
3388 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3389 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003390
Chris Lattnerd4252a72004-07-30 07:50:03 +00003391 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3392 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3393 std::string Op0Name = Op0->getName(); Op0->setName("");
3394 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3395 InsertNewInstBefore(Or, I);
3396 return BinaryOperator::createXor(Or,
3397 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003398 }
Chris Lattner183b3362004-04-09 19:05:30 +00003399
3400 // Try to fold constant and into select arguments.
3401 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003402 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003403 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003404 if (isa<PHINode>(Op0))
3405 if (Instruction *NV = FoldOpIntoPhi(I))
3406 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003407 }
3408
Chris Lattner330628a2006-01-06 17:59:59 +00003409 Value *A = 0, *B = 0;
3410 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003411
3412 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3413 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3414 return ReplaceInstUsesWith(I, Op1);
3415 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3416 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3417 return ReplaceInstUsesWith(I, Op0);
3418
Chris Lattnerb7845d62006-07-10 20:25:24 +00003419 // (A | B) | C and A | (B | C) -> bswap if possible.
3420 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003421 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003422 match(Op1, m_Or(m_Value(), m_Value())) ||
3423 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3424 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003425 if (Instruction *BSwap = MatchBSwap(I))
3426 return BSwap;
3427 }
3428
Chris Lattnerb62f5082005-05-09 04:58:36 +00003429 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3430 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003431 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003432 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3433 Op0->setName("");
3434 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3435 }
3436
3437 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3438 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003439 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003440 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3441 Op0->setName("");
3442 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3443 }
3444
Chris Lattner15212982005-09-18 03:42:07 +00003445 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003446 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003447 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3448
3449 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3450 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3451
3452
Chris Lattner01f56c62005-09-18 06:02:59 +00003453 // If we have: ((V + N) & C1) | (V & C2)
3454 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3455 // replace with V+N.
3456 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003457 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003458 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003459 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3460 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003461 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003462 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003463 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003464 return ReplaceInstUsesWith(I, A);
3465 }
3466 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003467 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003468 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3469 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003470 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003471 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003472 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003473 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003474 }
3475 }
3476 }
Chris Lattner812aab72003-08-12 19:11:07 +00003477
Chris Lattnerd4252a72004-07-30 07:50:03 +00003478 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3479 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003480 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003481 ConstantIntegral::getAllOnesValue(I.getType()));
3482 } else {
3483 A = 0;
3484 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003485 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003486 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3487 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003488 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003489 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003490
Misha Brukman9c003d82004-07-30 12:50:08 +00003491 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003492 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3493 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3494 I.getName()+".demorgan"), I);
3495 return BinaryOperator::createNot(And);
3496 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003497 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003498
Chris Lattner3ac7c262003-08-13 20:16:26 +00003499 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003500 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003501 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3502 return R;
3503
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003504 Value *LHSVal, *RHSVal;
3505 ConstantInt *LHSCst, *RHSCst;
3506 Instruction::BinaryOps LHSCC, RHSCC;
3507 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3508 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3509 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3510 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003511 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003512 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3513 // Ensure that the larger constant is on the RHS.
3514 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3515 SetCondInst *LHS = cast<SetCondInst>(Op0);
3516 if (cast<ConstantBool>(Cmp)->getValue()) {
3517 std::swap(LHS, RHS);
3518 std::swap(LHSCst, RHSCst);
3519 std::swap(LHSCC, RHSCC);
3520 }
3521
3522 // At this point, we know we have have two setcc instructions
3523 // comparing a value against two constants and or'ing the result
3524 // together. Because of the above check, we know that we only have
3525 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3526 // FoldSetCCLogical check above), that the two constants are not
3527 // equal.
3528 assert(LHSCst != RHSCst && "Compares not folded above?");
3529
3530 switch (LHSCC) {
3531 default: assert(0 && "Unknown integer condition code!");
3532 case Instruction::SetEQ:
3533 switch (RHSCC) {
3534 default: assert(0 && "Unknown integer condition code!");
3535 case Instruction::SetEQ:
3536 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3537 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3538 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3539 LHSVal->getName()+".off");
3540 InsertNewInstBefore(Add, I);
3541 const Type *UnsType = Add->getType()->getUnsignedVersion();
3542 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3543 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3544 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3545 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3546 }
3547 break; // (X == 13 | X == 15) -> no change
3548
Chris Lattner5c219462005-04-19 06:04:18 +00003549 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3550 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003551 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3552 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3553 return ReplaceInstUsesWith(I, RHS);
3554 }
3555 break;
3556 case Instruction::SetNE:
3557 switch (RHSCC) {
3558 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003559 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3560 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3561 return ReplaceInstUsesWith(I, LHS);
3562 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003563 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003564 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003565 }
3566 break;
3567 case Instruction::SetLT:
3568 switch (RHSCC) {
3569 default: assert(0 && "Unknown integer condition code!");
3570 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3571 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003572 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3573 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003574 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3575 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3576 return ReplaceInstUsesWith(I, RHS);
3577 }
3578 break;
3579 case Instruction::SetGT:
3580 switch (RHSCC) {
3581 default: assert(0 && "Unknown integer condition code!");
3582 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3583 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3584 return ReplaceInstUsesWith(I, LHS);
3585 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3586 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003587 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003588 }
3589 }
3590 }
3591 }
Chris Lattner3af10532006-05-05 06:39:07 +00003592
3593 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3594 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003595 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003596 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003597 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003598 // Only do this if the casts both really cause code to be generated.
3599 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3600 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003601 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3602 Op1C->getOperand(0),
3603 I.getName());
3604 InsertNewInstBefore(NewOp, I);
3605 return new CastInst(NewOp, I.getType());
3606 }
3607 }
3608
Chris Lattner15212982005-09-18 03:42:07 +00003609
Chris Lattner113f4f42002-06-25 16:13:24 +00003610 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003611}
3612
Chris Lattnerc2076352004-02-16 01:20:27 +00003613// XorSelf - Implements: X ^ X --> 0
3614struct XorSelf {
3615 Value *RHS;
3616 XorSelf(Value *rhs) : RHS(rhs) {}
3617 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3618 Instruction *apply(BinaryOperator &Xor) const {
3619 return &Xor;
3620 }
3621};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003622
3623
Chris Lattner113f4f42002-06-25 16:13:24 +00003624Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003625 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003626 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003627
Chris Lattner81a7a232004-10-16 18:11:37 +00003628 if (isa<UndefValue>(Op1))
3629 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3630
Chris Lattnerc2076352004-02-16 01:20:27 +00003631 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3632 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3633 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003634 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003635 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003636
3637 // See if we can simplify any instructions used by the instruction whose sole
3638 // purpose is to compute bits we don't care about.
3639 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003640 if (!isa<PackedType>(I.getType()) &&
3641 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003642 KnownZero, KnownOne))
3643 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003644
Chris Lattner97638592003-07-23 21:37:07 +00003645 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003646 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003647 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003648 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003649 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003650 return new SetCondInst(SCI->getInverseCondition(),
3651 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003652
Chris Lattner8f2f5982003-11-05 01:06:05 +00003653 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003654 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3655 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003656 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3657 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003658 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003659 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003660 }
Chris Lattner023a4832004-06-18 06:07:51 +00003661
3662 // ~(~X & Y) --> (X | ~Y)
3663 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3664 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3665 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3666 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003667 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003668 Op0I->getOperand(1)->getName()+".not");
3669 InsertNewInstBefore(NotY, I);
3670 return BinaryOperator::createOr(Op0NotVal, NotY);
3671 }
3672 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003673
Chris Lattner97638592003-07-23 21:37:07 +00003674 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003675 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003676 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003677 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003678 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3679 return BinaryOperator::createSub(
3680 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003681 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003682 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003683 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003684 } else if (Op0I->getOpcode() == Instruction::Or) {
3685 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3686 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3687 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3688 // Anything in both C1 and C2 is known to be zero, remove it from
3689 // NewRHS.
3690 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3691 NewRHS = ConstantExpr::getAnd(NewRHS,
3692 ConstantExpr::getNot(CommonBits));
3693 WorkList.push_back(Op0I);
3694 I.setOperand(0, Op0I->getOperand(0));
3695 I.setOperand(1, NewRHS);
3696 return &I;
3697 }
Chris Lattner97638592003-07-23 21:37:07 +00003698 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003699 }
Chris Lattner183b3362004-04-09 19:05:30 +00003700
3701 // Try to fold constant and into select arguments.
3702 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003703 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003704 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003705 if (isa<PHINode>(Op0))
3706 if (Instruction *NV = FoldOpIntoPhi(I))
3707 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003708 }
3709
Chris Lattnerbb74e222003-03-10 23:06:50 +00003710 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003711 if (X == Op1)
3712 return ReplaceInstUsesWith(I,
3713 ConstantIntegral::getAllOnesValue(I.getType()));
3714
Chris Lattnerbb74e222003-03-10 23:06:50 +00003715 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003716 if (X == Op0)
3717 return ReplaceInstUsesWith(I,
3718 ConstantIntegral::getAllOnesValue(I.getType()));
3719
Chris Lattnerdcd07922006-04-01 08:03:55 +00003720 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003721 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003722 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003723 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003724 I.swapOperands();
3725 std::swap(Op0, Op1);
3726 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003727 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003728 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003729 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003730 } else if (Op1I->getOpcode() == Instruction::Xor) {
3731 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3732 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3733 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3734 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003735 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3736 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3737 Op1I->swapOperands();
3738 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3739 I.swapOperands(); // Simplified below.
3740 std::swap(Op0, Op1);
3741 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003742 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003743
Chris Lattnerdcd07922006-04-01 08:03:55 +00003744 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003745 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003746 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003747 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003748 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003749 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3750 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003751 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003752 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003753 } else if (Op0I->getOpcode() == Instruction::Xor) {
3754 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3755 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3756 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3757 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003758 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3759 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3760 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003761 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3762 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003763 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3764 InsertNewInstBefore(N, I);
3765 return BinaryOperator::createAnd(N, Op1);
3766 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003767 }
3768
Chris Lattner3ac7c262003-08-13 20:16:26 +00003769 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3770 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3771 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3772 return R;
3773
Chris Lattner3af10532006-05-05 06:39:07 +00003774 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3775 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003776 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003777 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003778 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003779 // Only do this if the casts both really cause code to be generated.
3780 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3781 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003782 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3783 Op1C->getOperand(0),
3784 I.getName());
3785 InsertNewInstBefore(NewOp, I);
3786 return new CastInst(NewOp, I.getType());
3787 }
3788 }
3789
Chris Lattner113f4f42002-06-25 16:13:24 +00003790 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003791}
3792
Chris Lattner6862fbd2004-09-29 17:40:11 +00003793static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003794 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003795}
3796
3797/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3798/// overflowed for this type.
3799static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3800 ConstantInt *In2) {
3801 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3802
3803 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003804 return cast<ConstantInt>(Result)->getZExtValue() <
3805 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003806 if (isPositive(In1) != isPositive(In2))
3807 return false;
3808 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003809 return cast<ConstantInt>(Result)->getSExtValue() <
3810 cast<ConstantInt>(In1)->getSExtValue();
3811 return cast<ConstantInt>(Result)->getSExtValue() >
3812 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003813}
3814
Chris Lattner0798af32005-01-13 20:14:25 +00003815/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3816/// code necessary to compute the offset from the base pointer (without adding
3817/// in the base pointer). Return the result as a signed integer of intptr size.
3818static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3819 TargetData &TD = IC.getTargetData();
3820 gep_type_iterator GTI = gep_type_begin(GEP);
3821 const Type *UIntPtrTy = TD.getIntPtrType();
3822 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3823 Value *Result = Constant::getNullValue(SIntPtrTy);
3824
3825 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003826 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003827
Chris Lattner0798af32005-01-13 20:14:25 +00003828 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3829 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003830 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003831 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003832 SIntPtrTy);
3833 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3834 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003835 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003836 Scale = ConstantExpr::getMul(OpC, Scale);
3837 if (Constant *RC = dyn_cast<Constant>(Result))
3838 Result = ConstantExpr::getAdd(RC, Scale);
3839 else {
3840 // Emit an add instruction.
3841 Result = IC.InsertNewInstBefore(
3842 BinaryOperator::createAdd(Result, Scale,
3843 GEP->getName()+".offs"), I);
3844 }
3845 }
3846 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003847 // Convert to correct type.
3848 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3849 Op->getName()+".c"), I);
3850 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003851 // We'll let instcombine(mul) convert this to a shl if possible.
3852 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3853 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003854
3855 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003856 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003857 GEP->getName()+".offs"), I);
3858 }
3859 }
3860 return Result;
3861}
3862
3863/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3864/// else. At this point we know that the GEP is on the LHS of the comparison.
3865Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3866 Instruction::BinaryOps Cond,
3867 Instruction &I) {
3868 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003869
3870 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3871 if (isa<PointerType>(CI->getOperand(0)->getType()))
3872 RHS = CI->getOperand(0);
3873
Chris Lattner0798af32005-01-13 20:14:25 +00003874 Value *PtrBase = GEPLHS->getOperand(0);
3875 if (PtrBase == RHS) {
3876 // As an optimization, we don't actually have to compute the actual value of
3877 // OFFSET if this is a seteq or setne comparison, just return whether each
3878 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003879 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3880 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003881 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3882 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003883 bool EmitIt = true;
3884 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3885 if (isa<UndefValue>(C)) // undef index -> undef.
3886 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3887 if (C->isNullValue())
3888 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003889 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3890 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003891 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003892 return ReplaceInstUsesWith(I, // No comparison is needed here.
3893 ConstantBool::get(Cond == Instruction::SetNE));
3894 }
3895
3896 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003897 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003898 new SetCondInst(Cond, GEPLHS->getOperand(i),
3899 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3900 if (InVal == 0)
3901 InVal = Comp;
3902 else {
3903 InVal = InsertNewInstBefore(InVal, I);
3904 InsertNewInstBefore(Comp, I);
3905 if (Cond == Instruction::SetNE) // True if any are unequal
3906 InVal = BinaryOperator::createOr(InVal, Comp);
3907 else // True if all are equal
3908 InVal = BinaryOperator::createAnd(InVal, Comp);
3909 }
3910 }
3911 }
3912
3913 if (InVal)
3914 return InVal;
3915 else
3916 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3917 ConstantBool::get(Cond == Instruction::SetEQ));
3918 }
Chris Lattner0798af32005-01-13 20:14:25 +00003919
3920 // Only lower this if the setcc is the only user of the GEP or if we expect
3921 // the result to fold to a constant!
3922 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3923 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3924 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3925 return new SetCondInst(Cond, Offset,
3926 Constant::getNullValue(Offset->getType()));
3927 }
3928 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003929 // If the base pointers are different, but the indices are the same, just
3930 // compare the base pointer.
3931 if (PtrBase != GEPRHS->getOperand(0)) {
3932 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003933 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003934 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003935 if (IndicesTheSame)
3936 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3937 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3938 IndicesTheSame = false;
3939 break;
3940 }
3941
3942 // If all indices are the same, just compare the base pointers.
3943 if (IndicesTheSame)
3944 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3945 GEPRHS->getOperand(0));
3946
3947 // Otherwise, the base pointers are different and the indices are
3948 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003949 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003950 }
Chris Lattner0798af32005-01-13 20:14:25 +00003951
Chris Lattner81e84172005-01-13 22:25:21 +00003952 // If one of the GEPs has all zero indices, recurse.
3953 bool AllZeros = true;
3954 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3955 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3956 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3957 AllZeros = false;
3958 break;
3959 }
3960 if (AllZeros)
3961 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3962 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003963
3964 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003965 AllZeros = true;
3966 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3967 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3968 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3969 AllZeros = false;
3970 break;
3971 }
3972 if (AllZeros)
3973 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3974
Chris Lattner4fa89822005-01-14 00:20:05 +00003975 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3976 // If the GEPs only differ by one index, compare it.
3977 unsigned NumDifferences = 0; // Keep track of # differences.
3978 unsigned DiffOperand = 0; // The operand that differs.
3979 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3980 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003981 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3982 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003983 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003984 NumDifferences = 2;
3985 break;
3986 } else {
3987 if (NumDifferences++) break;
3988 DiffOperand = i;
3989 }
3990 }
3991
3992 if (NumDifferences == 0) // SAME GEP?
3993 return ReplaceInstUsesWith(I, // No comparison is needed here.
3994 ConstantBool::get(Cond == Instruction::SetEQ));
3995 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003996 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3997 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003998
3999 // Convert the operands to signed values to make sure to perform a
4000 // signed comparison.
4001 const Type *NewTy = LHSV->getType()->getSignedVersion();
4002 if (LHSV->getType() != NewTy)
4003 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
4004 LHSV->getName()), I);
4005 if (RHSV->getType() != NewTy)
4006 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
4007 RHSV->getName()), I);
4008 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004009 }
4010 }
4011
Chris Lattner0798af32005-01-13 20:14:25 +00004012 // Only lower this if the setcc is the only user of the GEP or if we expect
4013 // the result to fold to a constant!
4014 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4015 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4016 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4017 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4018 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4019 return new SetCondInst(Cond, L, R);
4020 }
4021 }
4022 return 0;
4023}
4024
4025
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004026Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004027 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4029 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004030
4031 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004032 if (Op0 == Op1)
4033 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004034
Chris Lattner81a7a232004-10-16 18:11:37 +00004035 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4036 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4037
Chris Lattner15ff1e12004-11-14 07:33:16 +00004038 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4039 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004040 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4041 isa<ConstantPointerNull>(Op0)) &&
4042 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004043 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004044 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4045
4046 // setcc's with boolean values can always be turned into bitwise operations
4047 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004048 switch (I.getOpcode()) {
4049 default: assert(0 && "Invalid setcc instruction!");
4050 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004051 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004052 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004053 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004054 }
Chris Lattner4456da62004-08-11 00:50:51 +00004055 case Instruction::SetNE:
4056 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004057
Chris Lattner4456da62004-08-11 00:50:51 +00004058 case Instruction::SetGT:
4059 std::swap(Op0, Op1); // Change setgt -> setlt
4060 // FALL THROUGH
4061 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4062 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4063 InsertNewInstBefore(Not, I);
4064 return BinaryOperator::createAnd(Not, Op1);
4065 }
4066 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004067 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004068 // FALL THROUGH
4069 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4070 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4071 InsertNewInstBefore(Not, I);
4072 return BinaryOperator::createOr(Not, Op1);
4073 }
4074 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004075 }
4076
Chris Lattner2dd01742004-06-09 04:24:29 +00004077 // See if we are doing a comparison between a constant and an instruction that
4078 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004079 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004080 // Check to see if we are comparing against the minimum or maximum value...
4081 if (CI->isMinValue()) {
4082 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004083 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004084 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004085 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004086 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4087 return BinaryOperator::createSetEQ(Op0, Op1);
4088 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4089 return BinaryOperator::createSetNE(Op0, Op1);
4090
4091 } else if (CI->isMaxValue()) {
4092 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004093 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004094 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004095 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004096 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4097 return BinaryOperator::createSetEQ(Op0, Op1);
4098 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4099 return BinaryOperator::createSetNE(Op0, Op1);
4100
4101 // Comparing against a value really close to min or max?
4102 } else if (isMinValuePlusOne(CI)) {
4103 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4104 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4105 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4106 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4107
4108 } else if (isMaxValueMinusOne(CI)) {
4109 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4110 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4111 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4112 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4113 }
4114
4115 // If we still have a setle or setge instruction, turn it into the
4116 // appropriate setlt or setgt instruction. Since the border cases have
4117 // already been handled above, this requires little checking.
4118 //
4119 if (I.getOpcode() == Instruction::SetLE)
4120 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4121 if (I.getOpcode() == Instruction::SetGE)
4122 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4123
Chris Lattneree0f2802006-02-12 02:07:56 +00004124
4125 // See if we can fold the comparison based on bits known to be zero or one
4126 // in the input.
4127 uint64_t KnownZero, KnownOne;
4128 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4129 KnownZero, KnownOne, 0))
4130 return &I;
4131
4132 // Given the known and unknown bits, compute a range that the LHS could be
4133 // in.
4134 if (KnownOne | KnownZero) {
4135 if (Ty->isUnsigned()) { // Unsigned comparison.
4136 uint64_t Min, Max;
4137 uint64_t RHSVal = CI->getZExtValue();
4138 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4139 Min, Max);
4140 switch (I.getOpcode()) { // LE/GE have been folded already.
4141 default: assert(0 && "Unknown setcc opcode!");
4142 case Instruction::SetEQ:
4143 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004144 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004145 break;
4146 case Instruction::SetNE:
4147 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004148 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004149 break;
4150 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004151 if (Max < RHSVal)
4152 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4153 if (Min > RHSVal)
4154 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004155 break;
4156 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004157 if (Min > RHSVal)
4158 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4159 if (Max < RHSVal)
4160 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004161 break;
4162 }
4163 } else { // Signed comparison.
4164 int64_t Min, Max;
4165 int64_t RHSVal = CI->getSExtValue();
4166 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4167 Min, Max);
4168 switch (I.getOpcode()) { // LE/GE have been folded already.
4169 default: assert(0 && "Unknown setcc opcode!");
4170 case Instruction::SetEQ:
4171 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004172 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004173 break;
4174 case Instruction::SetNE:
4175 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004176 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004177 break;
4178 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004179 if (Max < RHSVal)
4180 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4181 if (Min > RHSVal)
4182 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004183 break;
4184 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004185 if (Min > RHSVal)
4186 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4187 if (Max < RHSVal)
4188 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004189 break;
4190 }
4191 }
4192 }
4193
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004194 // Since the RHS is a constantInt (CI), if the left hand side is an
4195 // instruction, see if that instruction also has constants so that the
4196 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004197 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004198 switch (LHSI->getOpcode()) {
4199 case Instruction::And:
4200 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4201 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004202 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4203
4204 // If an operand is an AND of a truncating cast, we can widen the
4205 // and/compare to be the input width without changing the value
4206 // produced, eliminating a cast.
4207 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4208 // We can do this transformation if either the AND constant does not
4209 // have its sign bit set or if it is an equality comparison.
4210 // Extending a relational comparison when we're checking the sign
4211 // bit would not work.
4212 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4213 (I.isEquality() ||
4214 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4215 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4216 ConstantInt *NewCST;
4217 ConstantInt *NewCI;
4218 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004219 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004220 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004221 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004222 CI->getZExtValue());
4223 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004224 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004225 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004226 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004227 CI->getZExtValue());
4228 }
4229 Instruction *NewAnd =
4230 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4231 LHSI->getName());
4232 InsertNewInstBefore(NewAnd, I);
4233 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4234 }
4235 }
4236
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004237 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4238 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4239 // happens a LOT in code produced by the C front-end, for bitfield
4240 // access.
4241 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004242
4243 // Check to see if there is a noop-cast between the shift and the and.
4244 if (!Shift) {
4245 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4246 if (CI->getOperand(0)->getType()->isIntegral() &&
4247 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4248 CI->getType()->getPrimitiveSizeInBits())
4249 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4250 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004251
Reid Spencere0fc4df2006-10-20 07:07:24 +00004252 ConstantInt *ShAmt;
4253 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004254 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4255 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004256
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004257 // We can fold this as long as we can't shift unknown bits
4258 // into the mask. This can only happen with signed shift
4259 // rights, as they sign-extend.
4260 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004261 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004262 if (!CanFold) {
4263 // To test for the bad case of the signed shr, see if any
4264 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004265 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004266 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4267
Reid Spencere0fc4df2006-10-20 07:07:24 +00004268 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004269 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004270 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4271 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004272 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4273 CanFold = true;
4274 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004275
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004276 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004277 Constant *NewCst;
4278 if (Shift->getOpcode() == Instruction::Shl)
4279 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4280 else
4281 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004282
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004283 // Check to see if we are shifting out any of the bits being
4284 // compared.
4285 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4286 // If we shifted bits out, the fold is not going to work out.
4287 // As a special case, check to see if this means that the
4288 // result is always true or false now.
4289 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004290 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004291 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004292 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004293 } else {
4294 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004295 Constant *NewAndCST;
4296 if (Shift->getOpcode() == Instruction::Shl)
4297 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4298 else
4299 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4300 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004301 if (AndTy == Ty)
4302 LHSI->setOperand(0, Shift->getOperand(0));
4303 else {
4304 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4305 *Shift);
4306 LHSI->setOperand(0, NewCast);
4307 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004308 WorkList.push_back(Shift); // Shift is dead.
4309 AddUsesToWorkList(I);
4310 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004311 }
4312 }
Chris Lattner35167c32004-06-09 07:59:58 +00004313 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004314
4315 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4316 // preferable because it allows the C<<Y expression to be hoisted out
4317 // of a loop if Y is invariant and X is not.
4318 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004319 I.isEquality() && !Shift->isArithmeticShift() &&
4320 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004321 // Compute C << Y.
4322 Value *NS;
4323 if (Shift->getOpcode() == Instruction::Shr) {
4324 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4325 "tmp");
4326 } else {
4327 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004328 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004329 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004330 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004331 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004332 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4333 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004334 }
4335 InsertNewInstBefore(cast<Instruction>(NS), I);
4336
4337 // If C's sign doesn't agree with the and, insert a cast now.
4338 if (NS->getType() != LHSI->getType())
4339 NS = InsertCastBefore(NS, LHSI->getType(), I);
4340
4341 Value *ShiftOp = Shift->getOperand(0);
4342 if (ShiftOp->getType() != LHSI->getType())
4343 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4344
4345 // Compute X & (C << Y).
4346 Instruction *NewAnd =
4347 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4348 InsertNewInstBefore(NewAnd, I);
4349
4350 I.setOperand(0, NewAnd);
4351 return &I;
4352 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004353 }
4354 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004355
Chris Lattner272d5ca2004-09-28 18:22:15 +00004356 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004357 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004358 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004359 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4360
4361 // Check that the shift amount is in range. If not, don't perform
4362 // undefined shifts. When the shift is visited it will be
4363 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004364 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004365 break;
4366
Chris Lattner272d5ca2004-09-28 18:22:15 +00004367 // If we are comparing against bits always shifted out, the
4368 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004369 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004370 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4371 if (Comp != CI) {// Comparing against a bit that we know is zero.
4372 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4373 Constant *Cst = ConstantBool::get(IsSetNE);
4374 return ReplaceInstUsesWith(I, Cst);
4375 }
4376
4377 if (LHSI->hasOneUse()) {
4378 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004379 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004380 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4381
4382 Constant *Mask;
4383 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004384 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004385 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004386 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004387 } else {
4388 Mask = ConstantInt::getAllOnesValue(CI->getType());
4389 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004390
Chris Lattner272d5ca2004-09-28 18:22:15 +00004391 Instruction *AndI =
4392 BinaryOperator::createAnd(LHSI->getOperand(0),
4393 Mask, LHSI->getName()+".mask");
4394 Value *And = InsertNewInstBefore(AndI, I);
4395 return new SetCondInst(I.getOpcode(), And,
4396 ConstantExpr::getUShr(CI, ShAmt));
4397 }
4398 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004399 }
4400 break;
4401
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004402 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004403 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004404 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004405 // Check that the shift amount is in range. If not, don't perform
4406 // undefined shifts. When the shift is visited it will be
4407 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004408 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004409 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004410 break;
4411
Chris Lattner1023b872004-09-27 16:18:50 +00004412 // If we are comparing against bits always shifted out, the
4413 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004414 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004415 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004416
Chris Lattner1023b872004-09-27 16:18:50 +00004417 if (Comp != CI) {// Comparing against a bit that we know is zero.
4418 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4419 Constant *Cst = ConstantBool::get(IsSetNE);
4420 return ReplaceInstUsesWith(I, Cst);
4421 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004422
Chris Lattner1023b872004-09-27 16:18:50 +00004423 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004424 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004425
Chris Lattner1023b872004-09-27 16:18:50 +00004426 // Otherwise strength reduce the shift into an and.
4427 uint64_t Val = ~0ULL; // All ones.
4428 Val <<= ShAmtVal; // Shift over to the right spot.
4429
4430 Constant *Mask;
4431 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004432 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004433 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004434 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004435 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004436 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004437
Chris Lattner1023b872004-09-27 16:18:50 +00004438 Instruction *AndI =
4439 BinaryOperator::createAnd(LHSI->getOperand(0),
4440 Mask, LHSI->getName()+".mask");
4441 Value *And = InsertNewInstBefore(AndI, I);
4442 return new SetCondInst(I.getOpcode(), And,
4443 ConstantExpr::getShl(CI, ShAmt));
4444 }
Chris Lattner1023b872004-09-27 16:18:50 +00004445 }
4446 }
4447 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004448
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004449 case Instruction::SDiv:
4450 case Instruction::UDiv:
4451 // Fold: setcc ([us]div X, C1), C2 -> range test
4452 // Fold this div into the comparison, producing a range check.
4453 // Determine, based on the divide type, what the range is being
4454 // checked. If there is an overflow on the low or high side, remember
4455 // it, otherwise compute the range [low, hi) bounding the new value.
4456 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004457 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004458 // FIXME: If the operand types don't match the type of the divide
4459 // then don't attempt this transform. The code below doesn't have the
4460 // logic to deal with a signed divide and an unsigned compare (and
4461 // vice versa). This is because (x /s C1) <s C2 produces different
4462 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4463 // (x /u C1) <u C2. Simply casting the operands and result won't
4464 // work. :( The if statement below tests that condition and bails
4465 // if it finds it.
4466 const Type* DivRHSTy = DivRHS->getType();
4467 unsigned DivOpCode = LHSI->getOpcode();
4468 if (I.isEquality() &&
4469 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4470 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4471 break;
4472
4473 // Initialize the variables that will indicate the nature of the
4474 // range check.
4475 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004476 ConstantInt *LoBound = 0, *HiBound = 0;
4477
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004478 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4479 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4480 // C2 (CI). By solving for X we can turn this into a range check
4481 // instead of computing a divide.
4482 ConstantInt *Prod =
4483 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004484
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004485 // Determine if the product overflows by seeing if the product is
4486 // not equal to the divide. Make sure we do the same kind of divide
4487 // as in the LHS instruction that we're folding.
4488 bool ProdOV = !DivRHS->isNullValue() &&
4489 (DivOpCode == Instruction::SDiv ?
4490 ConstantExpr::getSDiv(Prod, DivRHS) :
4491 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4492
4493 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004494 Instruction::BinaryOps Opcode = I.getOpcode();
4495
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004496 if (DivRHS->isNullValue()) {
4497 // Don't hack on divide by zeros!
4498 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004499 LoBound = Prod;
4500 LoOverflow = ProdOV;
4501 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004502 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004503 if (CI->isNullValue()) { // (X / pos) op 0
4504 // Can't overflow.
4505 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4506 HiBound = DivRHS;
4507 } else if (isPositive(CI)) { // (X / pos) op pos
4508 LoBound = Prod;
4509 LoOverflow = ProdOV;
4510 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4511 } else { // (X / pos) op neg
4512 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4513 LoOverflow = AddWithOverflow(LoBound, Prod,
4514 cast<ConstantInt>(DivRHSH));
4515 HiBound = Prod;
4516 HiOverflow = ProdOV;
4517 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004518 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004519 if (CI->isNullValue()) { // (X / neg) op 0
4520 LoBound = AddOne(DivRHS);
4521 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004522 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004523 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004524 } else if (isPositive(CI)) { // (X / neg) op pos
4525 HiOverflow = LoOverflow = ProdOV;
4526 if (!LoOverflow)
4527 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4528 HiBound = AddOne(Prod);
4529 } else { // (X / neg) op neg
4530 LoBound = Prod;
4531 LoOverflow = HiOverflow = ProdOV;
4532 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4533 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004534
Chris Lattnera92af962004-10-11 19:40:04 +00004535 // Dividing by a negate swaps the condition.
4536 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004537 }
4538
4539 if (LoBound) {
4540 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004541 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004542 default: assert(0 && "Unhandled setcc opcode!");
4543 case Instruction::SetEQ:
4544 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004545 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004546 else if (HiOverflow)
4547 return new SetCondInst(Instruction::SetGE, X, LoBound);
4548 else if (LoOverflow)
4549 return new SetCondInst(Instruction::SetLT, X, HiBound);
4550 else
4551 return InsertRangeTest(X, LoBound, HiBound, true, I);
4552 case Instruction::SetNE:
4553 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004554 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004555 else if (HiOverflow)
4556 return new SetCondInst(Instruction::SetLT, X, LoBound);
4557 else if (LoOverflow)
4558 return new SetCondInst(Instruction::SetGE, X, HiBound);
4559 else
4560 return InsertRangeTest(X, LoBound, HiBound, false, I);
4561 case Instruction::SetLT:
4562 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004563 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004564 return new SetCondInst(Instruction::SetLT, X, LoBound);
4565 case Instruction::SetGT:
4566 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004567 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004568 return new SetCondInst(Instruction::SetGE, X, HiBound);
4569 }
4570 }
4571 }
4572 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004573 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004574
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004575 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004576 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004577 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4578
Reid Spencere0fc4df2006-10-20 07:07:24 +00004579 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4580 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4582 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004583#if 0
4584 case Instruction::SRem:
4585 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4586 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4587 BO->hasOneUse()) {
4588 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4589 if (V > 1 && isPowerOf2_64(V)) {
4590 Value *NewRem = InsertNewInstBefore(
4591 BinaryOperator::createURem(BO->getOperand(0),
4592 BO->getOperand(1),
4593 BO->getName()), I);
4594 return BinaryOperator::create(
4595 I.getOpcode(), NewRem,
4596 Constant::getNullValue(NewRem->getType()));
4597 }
4598 }
4599 break;
4600#endif
4601
Chris Lattner23b47b62004-07-06 07:38:18 +00004602 case Instruction::Rem:
4603 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004604 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4605 BO->hasOneUse() && BO->getOperand(1)->getType()->isSigned()) {
4606 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4607 if (V > 1 && isPowerOf2_64(V)) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004608 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004609 const Type *UTy = BO->getType()->getUnsignedVersion();
4610 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4611 UTy, "tmp"), I);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004612 Constant *RHSCst = ConstantInt::get(UTy, 1ULL << L2);
Chris Lattner23b47b62004-07-06 07:38:18 +00004613 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4614 RHSCst, BO->getName()), I);
4615 return BinaryOperator::create(I.getOpcode(), NewRem,
4616 Constant::getNullValue(UTy));
4617 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004618 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004619 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004620 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004621 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4622 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004623 if (BO->hasOneUse())
4624 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4625 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004626 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004627 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4628 // efficiently invertible, or if the add has just this one use.
4629 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004630
Chris Lattnerc992add2003-08-13 05:33:12 +00004631 if (Value *NegVal = dyn_castNegVal(BOp1))
4632 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4633 else if (Value *NegVal = dyn_castNegVal(BOp0))
4634 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004635 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004636 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4637 BO->setName("");
4638 InsertNewInstBefore(Neg, I);
4639 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4640 }
4641 }
4642 break;
4643 case Instruction::Xor:
4644 // For the xor case, we can xor two constants together, eliminating
4645 // the explicit xor.
4646 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4647 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004648 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004649
4650 // FALLTHROUGH
4651 case Instruction::Sub:
4652 // Replace (([sub|xor] A, B) != 0) with (A != B)
4653 if (CI->isNullValue())
4654 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4655 BO->getOperand(1));
4656 break;
4657
4658 case Instruction::Or:
4659 // If bits are being or'd in that are not present in the constant we
4660 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004661 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004662 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004663 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004664 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004665 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004666 break;
4667
4668 case Instruction::And:
4669 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004670 // If bits are being compared against that are and'd out, then the
4671 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004672 if (!ConstantExpr::getAnd(CI,
4673 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004674 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004675
Chris Lattner35167c32004-06-09 07:59:58 +00004676 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004677 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004678 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4679 Instruction::SetNE, Op0,
4680 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004681
Chris Lattnerc992add2003-08-13 05:33:12 +00004682 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4683 // to be a signed value as appropriate.
4684 if (isSignBit(BOC)) {
4685 Value *X = BO->getOperand(0);
4686 // If 'X' is not signed, insert a cast now...
4687 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004688 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004689 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004690 }
4691 return new SetCondInst(isSetNE ? Instruction::SetLT :
4692 Instruction::SetGE, X,
4693 Constant::getNullValue(X->getType()));
4694 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004695
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004696 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004697 if (CI->isNullValue() && isHighOnes(BOC)) {
4698 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004699 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004700
4701 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004702 if (NegX->getType()->isSigned()) {
4703 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4704 X = InsertCastBefore(X, DestTy, I);
4705 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004706 }
4707
4708 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004709 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004710 }
4711
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004712 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004713 default: break;
4714 }
4715 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004716 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004717 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004718 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4719 Value *CastOp = Cast->getOperand(0);
4720 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004721 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004722 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004723 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004724 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004725 "Source and destination signednesses should differ!");
4726 if (Cast->getType()->isSigned()) {
4727 // If this is a signed comparison, check for comparisons in the
4728 // vicinity of zero.
4729 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4730 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004731 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004732 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004733 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004734 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004735 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004736 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004737 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004738 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004739 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004740 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004741 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004742 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004743 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004744 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004745 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004746 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004747 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004748 return BinaryOperator::createSetLT(CastOp,
4749 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004750 }
4751 }
4752 }
Chris Lattnere967b342003-06-04 05:10:11 +00004753 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004754 }
4755
Chris Lattner77c32c32005-04-23 15:31:55 +00004756 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4757 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4758 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4759 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004760 case Instruction::GetElementPtr:
4761 if (RHSC->isNullValue()) {
4762 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4763 bool isAllZeros = true;
4764 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4765 if (!isa<Constant>(LHSI->getOperand(i)) ||
4766 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4767 isAllZeros = false;
4768 break;
4769 }
4770 if (isAllZeros)
4771 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4772 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4773 }
4774 break;
4775
Chris Lattner77c32c32005-04-23 15:31:55 +00004776 case Instruction::PHI:
4777 if (Instruction *NV = FoldOpIntoPhi(I))
4778 return NV;
4779 break;
4780 case Instruction::Select:
4781 // If either operand of the select is a constant, we can fold the
4782 // comparison into the select arms, which will cause one to be
4783 // constant folded and the select turned into a bitwise or.
4784 Value *Op1 = 0, *Op2 = 0;
4785 if (LHSI->hasOneUse()) {
4786 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4787 // Fold the known value into the constant operand.
4788 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4789 // Insert a new SetCC of the other select operand.
4790 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4791 LHSI->getOperand(2), RHSC,
4792 I.getName()), I);
4793 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4794 // Fold the known value into the constant operand.
4795 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4796 // Insert a new SetCC of the other select operand.
4797 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4798 LHSI->getOperand(1), RHSC,
4799 I.getName()), I);
4800 }
4801 }
Jeff Cohen82639852005-04-23 21:38:35 +00004802
Chris Lattner77c32c32005-04-23 15:31:55 +00004803 if (Op1)
4804 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4805 break;
4806 }
4807 }
4808
Chris Lattner0798af32005-01-13 20:14:25 +00004809 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4810 if (User *GEP = dyn_castGetElementPtr(Op0))
4811 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4812 return NI;
4813 if (User *GEP = dyn_castGetElementPtr(Op1))
4814 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4815 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4816 return NI;
4817
Chris Lattner16930792003-11-03 04:25:02 +00004818 // Test to see if the operands of the setcc are casted versions of other
4819 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004820 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4821 Value *CastOp0 = CI->getOperand(0);
4822 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004823 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004824 // We keep moving the cast from the left operand over to the right
4825 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004826 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004827
Chris Lattner16930792003-11-03 04:25:02 +00004828 // If operand #1 is a cast instruction, see if we can eliminate it as
4829 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004830 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4831 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004832 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004833 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004834
Chris Lattner16930792003-11-03 04:25:02 +00004835 // If Op1 is a constant, we can fold the cast into the constant.
4836 if (Op1->getType() != Op0->getType())
4837 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4838 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4839 } else {
4840 // Otherwise, cast the RHS right before the setcc
4841 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4842 InsertNewInstBefore(cast<Instruction>(Op1), I);
4843 }
4844 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4845 }
4846
Chris Lattner6444c372003-11-03 05:17:03 +00004847 // Handle the special case of: setcc (cast bool to X), <cst>
4848 // This comes up when you have code like
4849 // int X = A < B;
4850 // if (X) ...
4851 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004852 // with a constant or another cast from the same type.
4853 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4854 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4855 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004856 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004857
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004858 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004859 Value *A, *B;
4860 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4861 (A == Op1 || B == Op1)) {
4862 // (A^B) == A -> B == 0
4863 Value *OtherVal = A == Op1 ? B : A;
4864 return BinaryOperator::create(I.getOpcode(), OtherVal,
4865 Constant::getNullValue(A->getType()));
4866 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4867 (A == Op0 || B == Op0)) {
4868 // A == (A^B) -> B == 0
4869 Value *OtherVal = A == Op0 ? B : A;
4870 return BinaryOperator::create(I.getOpcode(), OtherVal,
4871 Constant::getNullValue(A->getType()));
4872 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4873 // (A-B) == A -> B == 0
4874 return BinaryOperator::create(I.getOpcode(), B,
4875 Constant::getNullValue(B->getType()));
4876 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4877 // A == (A-B) -> B == 0
4878 return BinaryOperator::create(I.getOpcode(), B,
4879 Constant::getNullValue(B->getType()));
4880 }
4881 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004882 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004883}
4884
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004885// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4886// We only handle extending casts so far.
4887//
4888Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4889 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4890 const Type *SrcTy = LHSCIOp->getType();
4891 const Type *DestTy = SCI.getOperand(0)->getType();
4892 Value *RHSCIOp;
4893
4894 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004895 return 0;
4896
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004897 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4898 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4899 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4900
4901 // Is this a sign or zero extension?
4902 bool isSignSrc = SrcTy->isSigned();
4903 bool isSignDest = DestTy->isSigned();
4904
4905 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4906 // Not an extension from the same type?
4907 RHSCIOp = CI->getOperand(0);
4908 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4909 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4910 // Compute the constant that would happen if we truncated to SrcTy then
4911 // reextended to DestTy.
4912 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4913
4914 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00004915 // Make sure that src sign and dest sign match. For example,
4916 //
4917 // %A = cast short %X to uint
4918 // %B = setgt uint %A, 1330
4919 //
Devang Patel88afd002006-10-19 19:21:36 +00004920 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00004921 //
4922 // %B = setgt short %X, 1330
4923 //
4924 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00004925 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4926 // OR operation is EQ/NE.
4927 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00004928 RHSCIOp = Res;
4929 else
4930 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004931 } else {
4932 // If the value cannot be represented in the shorter type, we cannot emit
4933 // a simple comparison.
4934 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004935 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004936 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004937 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004938
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004939 // Evaluate the comparison for LT.
4940 Value *Result;
4941 if (DestTy->isSigned()) {
4942 // We're performing a signed comparison.
4943 if (isSignSrc) {
4944 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004945 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004946 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004947 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00004948 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004949 } else {
4950 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004951 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004952 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004953 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004954 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004955 }
4956 } else {
4957 // We're performing an unsigned comparison.
4958 if (!isSignSrc) {
4959 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004960 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004961 } else {
4962 // We're performing an unsigned comp with a sign extended value.
4963 // This is true if the input is >= 0. [aka >s -1]
4964 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4965 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4966 NegOne, SCI.getName()), SCI);
4967 }
Reid Spencer279fa252004-11-28 21:31:15 +00004968 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004969
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004970 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004971 if (SCI.getOpcode() == Instruction::SetLT) {
4972 return ReplaceInstUsesWith(SCI, Result);
4973 } else {
4974 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4975 if (Constant *CI = dyn_cast<Constant>(Result))
4976 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4977 else
4978 return BinaryOperator::createNot(Result);
4979 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004980 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004981 } else {
4982 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004983 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004984
Chris Lattner252a8452005-06-16 03:00:08 +00004985 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004986 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4987}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004988
Chris Lattnere8d6c602003-03-10 19:16:08 +00004989Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004990 assert(I.getOperand(1)->getType() == Type::UByteTy);
4991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004992 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004993
4994 // shl X, 0 == X and shr X, 0 == X
4995 // shl 0, X == 0 and shr 0, X == 0
4996 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004997 Op0 == Constant::getNullValue(Op0->getType()))
4998 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004999
Chris Lattner81a7a232004-10-16 18:11:37 +00005000 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5001 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005002 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005003 else // undef << X -> 0 AND undef >>u X -> 0
5004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5005 }
5006 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005007 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005008 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5009 else
5010 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5011 }
5012
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005013 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
5014 if (!isLeftShift)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005015 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner5dee3b22006-10-20 18:20:21 +00005016 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005017 return ReplaceInstUsesWith(I, CSI);
5018
Chris Lattner183b3362004-04-09 19:05:30 +00005019 // Try to fold constant and into select arguments.
5020 if (isa<Constant>(Op0))
5021 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005022 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005023 return R;
5024
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005025 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005026 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005027 if (MaskedValueIsZero(Op0,
5028 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005029 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
5030 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
5031 I.getName()), I);
5032 return new CastInst(V, I.getType());
5033 }
5034 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005035
Reid Spencere0fc4df2006-10-20 07:07:24 +00005036 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5037 if (CUI->getType()->isUnsigned())
5038 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5039 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005040 return 0;
5041}
5042
Reid Spencere0fc4df2006-10-20 07:07:24 +00005043Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005044 ShiftInst &I) {
5045 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00005046 bool isSignedShift = Op0->getType()->isSigned();
5047 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005048
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005049 // See if we can simplify any instructions used by the instruction whose sole
5050 // purpose is to compute bits we don't care about.
5051 uint64_t KnownZero, KnownOne;
5052 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5053 KnownZero, KnownOne))
5054 return &I;
5055
Chris Lattner14553932006-01-06 07:12:35 +00005056 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5057 // of a signed value.
5058 //
5059 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005060 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005061 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005062 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5063 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005064 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005065 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005066 }
Chris Lattner14553932006-01-06 07:12:35 +00005067 }
5068
5069 // ((X*C1) << C2) == (X * (C1 << C2))
5070 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5071 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5072 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5073 return BinaryOperator::createMul(BO->getOperand(0),
5074 ConstantExpr::getShl(BOOp, Op1));
5075
5076 // Try to fold constant and into select arguments.
5077 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5078 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5079 return R;
5080 if (isa<PHINode>(Op0))
5081 if (Instruction *NV = FoldOpIntoPhi(I))
5082 return NV;
5083
5084 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005085 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5086 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5087 Value *V1, *V2;
5088 ConstantInt *CC;
5089 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005090 default: break;
5091 case Instruction::Add:
5092 case Instruction::And:
5093 case Instruction::Or:
5094 case Instruction::Xor:
5095 // These operators commute.
5096 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005097 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5098 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005099 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005100 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005101 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005102 Op0BO->getName());
5103 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005104 Instruction *X =
5105 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5106 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005107 InsertNewInstBefore(X, I); // (X + (Y << C))
5108 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005109 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005110 return BinaryOperator::createAnd(X, C2);
5111 }
Chris Lattner14553932006-01-06 07:12:35 +00005112
Chris Lattner797dee72005-09-18 06:30:59 +00005113 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5114 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5115 match(Op0BO->getOperand(1),
5116 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005117 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005118 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005119 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005120 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005121 Op0BO->getName());
5122 InsertNewInstBefore(YS, I); // (Y << C)
5123 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005124 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005125 V1->getName()+".mask");
5126 InsertNewInstBefore(XM, I); // X & (CC << C)
5127
5128 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5129 }
Chris Lattner14553932006-01-06 07:12:35 +00005130
Chris Lattner797dee72005-09-18 06:30:59 +00005131 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005132 case Instruction::Sub:
5133 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005134 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5135 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005136 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005137 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005138 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005139 Op0BO->getName());
5140 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005141 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005142 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005143 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005144 InsertNewInstBefore(X, I); // (X + (Y << C))
5145 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005146 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005147 return BinaryOperator::createAnd(X, C2);
5148 }
Chris Lattner14553932006-01-06 07:12:35 +00005149
Chris Lattner1df0e982006-05-31 21:14:00 +00005150 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005151 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5152 match(Op0BO->getOperand(0),
5153 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005154 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005155 cast<BinaryOperator>(Op0BO->getOperand(0))
5156 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005157 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005158 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005159 Op0BO->getName());
5160 InsertNewInstBefore(YS, I); // (Y << C)
5161 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005162 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005163 V1->getName()+".mask");
5164 InsertNewInstBefore(XM, I); // X & (CC << C)
5165
Chris Lattner1df0e982006-05-31 21:14:00 +00005166 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005167 }
Chris Lattner14553932006-01-06 07:12:35 +00005168
Chris Lattner27cb9db2005-09-18 05:12:10 +00005169 break;
Chris Lattner14553932006-01-06 07:12:35 +00005170 }
5171
5172
5173 // If the operand is an bitwise operator with a constant RHS, and the
5174 // shift is the only use, we can pull it out of the shift.
5175 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5176 bool isValid = true; // Valid only for And, Or, Xor
5177 bool highBitSet = false; // Transform if high bit of constant set?
5178
5179 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005180 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005181 case Instruction::Add:
5182 isValid = isLeftShift;
5183 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005184 case Instruction::Or:
5185 case Instruction::Xor:
5186 highBitSet = false;
5187 break;
5188 case Instruction::And:
5189 highBitSet = true;
5190 break;
Chris Lattner14553932006-01-06 07:12:35 +00005191 }
5192
5193 // If this is a signed shift right, and the high bit is modified
5194 // by the logical operation, do not perform the transformation.
5195 // The highBitSet boolean indicates the value of the high bit of
5196 // the constant which would cause it to be modified for this
5197 // operation.
5198 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005199 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005200 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005201 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5202 }
5203
5204 if (isValid) {
5205 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5206
5207 Instruction *NewShift =
5208 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5209 Op0BO->getName());
5210 Op0BO->setName("");
5211 InsertNewInstBefore(NewShift, I);
5212
5213 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5214 NewRHS);
5215 }
5216 }
5217 }
5218 }
5219
Chris Lattnereb372a02006-01-06 07:52:12 +00005220 // Find out if this is a shift of a shift by a constant.
5221 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005222 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005223 ShiftOp = Op0SI;
5224 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5225 // If this is a noop-integer case of a shift instruction, use the shift.
5226 if (CI->getOperand(0)->getType()->isInteger() &&
5227 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5228 CI->getType()->getPrimitiveSizeInBits() &&
5229 isa<ShiftInst>(CI->getOperand(0))) {
5230 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5231 }
5232 }
5233
Reid Spencere0fc4df2006-10-20 07:07:24 +00005234 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005235 // Find the operands and properties of the input shift. Note that the
5236 // signedness of the input shift may differ from the current shift if there
5237 // is a noop cast between the two.
5238 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5239 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005240 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005241
Reid Spencere0fc4df2006-10-20 07:07:24 +00005242 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005243
Reid Spencere0fc4df2006-10-20 07:07:24 +00005244 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5245 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005246
5247 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5248 if (isLeftShift == isShiftOfLeftShift) {
5249 // Do not fold these shifts if the first one is signed and the second one
5250 // is unsigned and this is a right shift. Further, don't do any folding
5251 // on them.
5252 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5253 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005254
Chris Lattnereb372a02006-01-06 07:52:12 +00005255 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5256 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5257 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005258
Chris Lattnereb372a02006-01-06 07:52:12 +00005259 Value *Op = ShiftOp->getOperand(0);
5260 if (isShiftOfSignedShift != isSignedShift)
5261 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5262 return new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005263 ConstantInt::get(Type::UByteTy, Amt));
Chris Lattnereb372a02006-01-06 07:52:12 +00005264 }
5265
5266 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5267 // signed types, we can only support the (A >> c1) << c2 configuration,
5268 // because it can not turn an arbitrary bit of A into a sign bit.
5269 if (isUnsignedShift || isLeftShift) {
5270 // Calculate bitmask for what gets shifted off the edge.
5271 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5272 if (isLeftShift)
5273 C = ConstantExpr::getShl(C, ShiftAmt1C);
5274 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005275 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005276
5277 Value *Op = ShiftOp->getOperand(0);
5278 if (isShiftOfSignedShift != isSignedShift)
5279 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
5280
5281 Instruction *Mask =
5282 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5283 InsertNewInstBefore(Mask, I);
5284
5285 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005286 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005287 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005288 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005289 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005290 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005291 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5292 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5293 // Make sure to emit an unsigned shift right, not a signed one.
5294 Mask = InsertNewInstBefore(new CastInst(Mask,
5295 Mask->getType()->getUnsignedVersion(),
5296 Op->getName()), I);
5297 Mask = new ShiftInst(Instruction::Shr, Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005298 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005299 InsertNewInstBefore(Mask, I);
5300 return new CastInst(Mask, I.getType());
5301 } else {
5302 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005303 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005304 }
5305 } else {
5306 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5307 Op = InsertNewInstBefore(new CastInst(Mask,
5308 I.getType()->getSignedVersion(),
5309 Mask->getName()), I);
5310 Instruction *Shift =
5311 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005312 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005313 InsertNewInstBefore(Shift, I);
5314
5315 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5316 C = ConstantExpr::getShl(C, Op1);
5317 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5318 InsertNewInstBefore(Mask, I);
5319 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005320 }
5321 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005322 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005323 // this case, C1 == C2 and C1 is 8, 16, or 32.
5324 if (ShiftAmt1 == ShiftAmt2) {
5325 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005326 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005327 case 8 : SExtType = Type::SByteTy; break;
5328 case 16: SExtType = Type::ShortTy; break;
5329 case 32: SExtType = Type::IntTy; break;
5330 }
5331
5332 if (SExtType) {
5333 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5334 SExtType, "sext");
5335 InsertNewInstBefore(NewTrunc, I);
5336 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005337 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005338 }
Chris Lattner86102b82005-01-01 16:22:27 +00005339 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005340 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005341 return 0;
5342}
5343
Chris Lattner48a44f72002-05-02 17:06:02 +00005344
Chris Lattner8f663e82005-10-29 04:36:15 +00005345/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5346/// expression. If so, decompose it, returning some value X, such that Val is
5347/// X*Scale+Offset.
5348///
5349static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5350 unsigned &Offset) {
5351 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005352 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5353 if (CI->getType()->isUnsigned()) {
5354 Offset = CI->getZExtValue();
5355 Scale = 1;
5356 return ConstantInt::get(Type::UIntTy, 0);
5357 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005358 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5359 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005360 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5361 if (CUI->getType()->isUnsigned()) {
5362 if (I->getOpcode() == Instruction::Shl) {
5363 // This is a value scaled by '1 << the shift amt'.
5364 Scale = 1U << CUI->getZExtValue();
5365 Offset = 0;
5366 return I->getOperand(0);
5367 } else if (I->getOpcode() == Instruction::Mul) {
5368 // This value is scaled by 'CUI'.
5369 Scale = CUI->getZExtValue();
5370 Offset = 0;
5371 return I->getOperand(0);
5372 } else if (I->getOpcode() == Instruction::Add) {
5373 // We have X+C. Check to see if we really have (X*C2)+C1,
5374 // where C1 is divisible by C2.
5375 unsigned SubScale;
5376 Value *SubVal =
5377 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5378 Offset += CUI->getZExtValue();
5379 if (SubScale > 1 && (Offset % SubScale == 0)) {
5380 Scale = SubScale;
5381 return SubVal;
5382 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005383 }
5384 }
5385 }
5386 }
5387 }
5388
5389 // Otherwise, we can't look past this.
5390 Scale = 1;
5391 Offset = 0;
5392 return Val;
5393}
5394
5395
Chris Lattner216be912005-10-24 06:03:58 +00005396/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5397/// try to eliminate the cast by moving the type information into the alloc.
5398Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5399 AllocationInst &AI) {
5400 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005401 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005402
Chris Lattnerac87beb2005-10-24 06:22:12 +00005403 // Remove any uses of AI that are dead.
5404 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5405 std::vector<Instruction*> DeadUsers;
5406 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5407 Instruction *User = cast<Instruction>(*UI++);
5408 if (isInstructionTriviallyDead(User)) {
5409 while (UI != E && *UI == User)
5410 ++UI; // If this instruction uses AI more than once, don't break UI.
5411
5412 // Add operands to the worklist.
5413 AddUsesToWorkList(*User);
5414 ++NumDeadInst;
5415 DEBUG(std::cerr << "IC: DCE: " << *User);
5416
5417 User->eraseFromParent();
5418 removeFromWorkList(User);
5419 }
5420 }
5421
Chris Lattner216be912005-10-24 06:03:58 +00005422 // Get the type really allocated and the type casted to.
5423 const Type *AllocElTy = AI.getAllocatedType();
5424 const Type *CastElTy = PTy->getElementType();
5425 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005426
Chris Lattner7d190672006-10-01 19:40:58 +00005427 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5428 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005429 if (CastElTyAlign < AllocElTyAlign) return 0;
5430
Chris Lattner46705b22005-10-24 06:35:18 +00005431 // If the allocation has multiple uses, only promote it if we are strictly
5432 // increasing the alignment of the resultant allocation. If we keep it the
5433 // same, we open the door to infinite loops of various kinds.
5434 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5435
Chris Lattner216be912005-10-24 06:03:58 +00005436 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5437 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005438 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005439
Chris Lattner8270c332005-10-29 03:19:53 +00005440 // See if we can satisfy the modulus by pulling a scale out of the array
5441 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005442 unsigned ArraySizeScale, ArrayOffset;
5443 Value *NumElements = // See if the array size is a decomposable linear expr.
5444 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5445
Chris Lattner8270c332005-10-29 03:19:53 +00005446 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5447 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005448 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5449 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005450
Chris Lattner8270c332005-10-29 03:19:53 +00005451 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5452 Value *Amt = 0;
5453 if (Scale == 1) {
5454 Amt = NumElements;
5455 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005456 // If the allocation size is constant, form a constant mul expression
5457 Amt = ConstantInt::get(Type::UIntTy, Scale);
5458 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5459 Amt = ConstantExpr::getMul(
5460 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5461 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005462 else if (Scale != 1) {
5463 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5464 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005465 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005466 }
5467
Chris Lattner8f663e82005-10-29 04:36:15 +00005468 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005469 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005470 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5471 Amt = InsertNewInstBefore(Tmp, AI);
5472 }
5473
Chris Lattner216be912005-10-24 06:03:58 +00005474 std::string Name = AI.getName(); AI.setName("");
5475 AllocationInst *New;
5476 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005477 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005478 else
Nate Begeman848622f2005-11-05 09:21:28 +00005479 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005480 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005481
5482 // If the allocation has multiple uses, insert a cast and change all things
5483 // that used it to use the new cast. This will also hack on CI, but it will
5484 // die soon.
5485 if (!AI.hasOneUse()) {
5486 AddUsesToWorkList(AI);
5487 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5488 InsertNewInstBefore(NewCast, AI);
5489 AI.replaceAllUsesWith(NewCast);
5490 }
Chris Lattner216be912005-10-24 06:03:58 +00005491 return ReplaceInstUsesWith(CI, New);
5492}
5493
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005494/// CanEvaluateInDifferentType - Return true if we can take the specified value
5495/// and return it without inserting any new casts. This is used by code that
5496/// tries to decide whether promoting or shrinking integer operations to wider
5497/// or smaller types will allow us to eliminate a truncate or extend.
5498static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5499 int &NumCastsRemoved) {
5500 if (isa<Constant>(V)) return true;
5501
5502 Instruction *I = dyn_cast<Instruction>(V);
5503 if (!I || !I->hasOneUse()) return false;
5504
5505 switch (I->getOpcode()) {
5506 case Instruction::And:
5507 case Instruction::Or:
5508 case Instruction::Xor:
5509 // These operators can all arbitrarily be extended or truncated.
5510 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5511 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5512 case Instruction::Cast:
5513 // If this is a cast from the destination type, we can trivially eliminate
5514 // it, and this will remove a cast overall.
5515 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005516 // If the first operand is itself a cast, and is eliminable, do not count
5517 // this as an eliminable cast. We would prefer to eliminate those two
5518 // casts first.
5519 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5520 return true;
5521
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005522 ++NumCastsRemoved;
5523 return true;
5524 }
5525 // TODO: Can handle more cases here.
5526 break;
5527 }
5528
5529 return false;
5530}
5531
5532/// EvaluateInDifferentType - Given an expression that
5533/// CanEvaluateInDifferentType returns true for, actually insert the code to
5534/// evaluate the expression.
5535Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5536 if (Constant *C = dyn_cast<Constant>(V))
5537 return ConstantExpr::getCast(C, Ty);
5538
5539 // Otherwise, it must be an instruction.
5540 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005541 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005542 switch (I->getOpcode()) {
5543 case Instruction::And:
5544 case Instruction::Or:
5545 case Instruction::Xor: {
5546 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5547 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5548 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5549 LHS, RHS, I->getName());
5550 break;
5551 }
5552 case Instruction::Cast:
5553 // If this is a cast from the destination type, return the input.
5554 if (I->getOperand(0)->getType() == Ty)
5555 return I->getOperand(0);
5556
5557 // TODO: Can handle more cases here.
5558 assert(0 && "Unreachable!");
5559 break;
5560 }
5561
5562 return InsertNewInstBefore(Res, *I);
5563}
5564
Chris Lattner216be912005-10-24 06:03:58 +00005565
Chris Lattner48a44f72002-05-02 17:06:02 +00005566// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005567//
Chris Lattner113f4f42002-06-25 16:13:24 +00005568Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005569 Value *Src = CI.getOperand(0);
5570
Chris Lattner48a44f72002-05-02 17:06:02 +00005571 // If the user is casting a value to the same type, eliminate this cast
5572 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005573 if (CI.getType() == Src->getType())
5574 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005575
Chris Lattner81a7a232004-10-16 18:11:37 +00005576 if (isa<UndefValue>(Src)) // cast undef -> undef
5577 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5578
Chris Lattner48a44f72002-05-02 17:06:02 +00005579 // If casting the result of another cast instruction, try to eliminate this
5580 // one!
5581 //
Chris Lattner86102b82005-01-01 16:22:27 +00005582 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5583 Value *A = CSrc->getOperand(0);
5584 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5585 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005586 // This instruction now refers directly to the cast's src operand. This
5587 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005588 CI.setOperand(0, CSrc->getOperand(0));
5589 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005590 }
5591
Chris Lattner650b6da2002-08-02 20:00:25 +00005592 // If this is an A->B->A cast, and we are dealing with integral types, try
5593 // to convert this into a logical 'and' instruction.
5594 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005595 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005596 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005597 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005598 CSrc->getType()->getPrimitiveSizeInBits() <
5599 CI.getType()->getPrimitiveSizeInBits()&&
5600 A->getType()->getPrimitiveSizeInBits() ==
5601 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005602 assert(CSrc->getType() != Type::ULongTy &&
5603 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005604 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005605 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005606 AndValue);
5607 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5608 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5609 if (And->getType() != CI.getType()) {
5610 And->setName(CSrc->getName()+".mask");
5611 InsertNewInstBefore(And, CI);
5612 And = new CastInst(And, CI.getType());
5613 }
5614 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005615 }
5616 }
Chris Lattner2590e512006-02-07 06:56:34 +00005617
Chris Lattner03841652004-05-25 04:29:21 +00005618 // If this is a cast to bool, turn it into the appropriate setne instruction.
5619 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005620 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005621 Constant::getNullValue(CI.getOperand(0)->getType()));
5622
Chris Lattner2590e512006-02-07 06:56:34 +00005623 // See if we can simplify any instructions used by the LHS whose sole
5624 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005625 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5626 uint64_t KnownZero, KnownOne;
5627 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5628 KnownZero, KnownOne))
5629 return &CI;
5630 }
Chris Lattner2590e512006-02-07 06:56:34 +00005631
Chris Lattnerd0d51602003-06-21 23:12:02 +00005632 // If casting the result of a getelementptr instruction with no offset, turn
5633 // this into a cast of the original pointer!
5634 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005635 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005636 bool AllZeroOperands = true;
5637 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5638 if (!isa<Constant>(GEP->getOperand(i)) ||
5639 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5640 AllZeroOperands = false;
5641 break;
5642 }
5643 if (AllZeroOperands) {
5644 CI.setOperand(0, GEP->getOperand(0));
5645 return &CI;
5646 }
5647 }
5648
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005649 // If we are casting a malloc or alloca to a pointer to a type of the same
5650 // size, rewrite the allocation instruction to allocate the "right" type.
5651 //
5652 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005653 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5654 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005655
Chris Lattner86102b82005-01-01 16:22:27 +00005656 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5657 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5658 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005659 if (isa<PHINode>(Src))
5660 if (Instruction *NV = FoldOpIntoPhi(CI))
5661 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005662
5663 // If the source and destination are pointers, and this cast is equivalent to
5664 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5665 // This can enhance SROA and other transforms that want type-safe pointers.
5666 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5667 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5668 const Type *DstTy = DstPTy->getElementType();
5669 const Type *SrcTy = SrcPTy->getElementType();
5670
5671 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5672 unsigned NumZeros = 0;
5673 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005674 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5675 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005676 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5677 ++NumZeros;
5678 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005679
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005680 // If we found a path from the src to dest, create the getelementptr now.
5681 if (SrcTy == DstTy) {
5682 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5683 return new GetElementPtrInst(Src, Idxs);
5684 }
5685 }
5686
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005687 // If the source value is an instruction with only this use, we can attempt to
5688 // propagate the cast into the instruction. Also, only handle integral types
5689 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005690 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005691 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005692 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005693
5694 int NumCastsRemoved = 0;
5695 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5696 // If this cast is a truncate, evaluting in a different type always
5697 // eliminates the cast, so it is always a win. If this is a noop-cast
5698 // this just removes a noop cast which isn't pointful, but simplifies
5699 // the code. If this is a zero-extension, we need to do an AND to
5700 // maintain the clear top-part of the computation, so we require that
5701 // the input have eliminated at least one cast. If this is a sign
5702 // extension, we insert two new casts (to do the extension) so we
5703 // require that two casts have been eliminated.
5704 bool DoXForm;
5705 switch (getCastType(Src->getType(), CI.getType())) {
5706 default: assert(0 && "Unknown cast type!");
5707 case Noop:
5708 case Truncate:
5709 DoXForm = true;
5710 break;
5711 case Zeroext:
5712 DoXForm = NumCastsRemoved >= 1;
5713 break;
5714 case Signext:
5715 DoXForm = NumCastsRemoved >= 2;
5716 break;
5717 }
5718
5719 if (DoXForm) {
5720 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5721 assert(Res->getType() == CI.getType());
5722 switch (getCastType(Src->getType(), CI.getType())) {
5723 default: assert(0 && "Unknown cast type!");
5724 case Noop:
5725 case Truncate:
5726 // Just replace this cast with the result.
5727 return ReplaceInstUsesWith(CI, Res);
5728 case Zeroext: {
5729 // We need to emit an AND to clear the high bits.
5730 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5731 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5732 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005733 Constant *C =
5734 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005735 C = ConstantExpr::getCast(C, CI.getType());
5736 return BinaryOperator::createAnd(Res, C);
5737 }
5738 case Signext:
5739 // We need to emit a cast to truncate, then a cast to sext.
5740 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5741 CI.getType());
5742 }
5743 }
5744 }
5745
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005746 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005747 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5748 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005749
5750 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5751 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5752
5753 switch (SrcI->getOpcode()) {
5754 case Instruction::Add:
5755 case Instruction::Mul:
5756 case Instruction::And:
5757 case Instruction::Or:
5758 case Instruction::Xor:
5759 // If we are discarding information, or just changing the sign, rewrite.
5760 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5761 // Don't insert two casts if they cannot be eliminated. We allow two
5762 // casts to be inserted if the sizes are the same. This could only be
5763 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005764 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5765 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005766 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5767 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5768 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5769 ->getOpcode(), Op0c, Op1c);
5770 }
5771 }
Chris Lattner72086162005-05-06 02:07:39 +00005772
5773 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5774 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005775 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005776 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5777 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5778 return BinaryOperator::createXor(New,
5779 ConstantInt::get(CI.getType(), 1));
5780 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005781 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005782 case Instruction::SDiv:
5783 case Instruction::UDiv:
5784 // If we are just changing the sign, rewrite.
5785 if (DestBitSize == SrcBitSize) {
5786 // Don't insert two casts if they cannot be eliminated. We allow two
5787 // casts to be inserted if the sizes are the same. This could only be
5788 // converting signedness, which is a noop.
5789 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5790 !ValueRequiresCast(Op0, DestTy, TD)) {
5791 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5792 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5793 return BinaryOperator::create(
5794 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5795 }
5796 }
5797 break;
5798
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005799 case Instruction::Shl:
5800 // Allow changing the sign of the source operand. Do not allow changing
5801 // the size of the shift, UNLESS the shift amount is a constant. We
5802 // mush not change variable sized shifts to a smaller size, because it
5803 // is undefined to shift more bits out than exist in the value.
5804 if (DestBitSize == SrcBitSize ||
5805 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5806 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5807 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5808 }
5809 break;
Chris Lattner87380412005-05-06 04:18:52 +00005810 case Instruction::Shr:
5811 // If this is a signed shr, and if all bits shifted in are about to be
5812 // truncated off, turn it into an unsigned shr to allow greater
5813 // simplifications.
5814 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5815 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005816 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005817 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5818 // Convert to unsigned.
5819 Value *N1 = InsertOperandCastBefore(Op0,
5820 Op0->getType()->getUnsignedVersion(), &CI);
5821 // Insert the new shift, which is now unsigned.
5822 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5823 Op1, Src->getName()), CI);
5824 return new CastInst(N1, CI.getType());
5825 }
5826 }
5827 break;
5828
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005829 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005830 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005831 // We if we are just checking for a seteq of a single bit and casting it
5832 // to an integer. If so, shift the bit to the appropriate place then
5833 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005834 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005835 uint64_t Op1CV = Op1C->getZExtValue();
5836 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5837 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5838 // cast (X == 1) to int --> X iff X has only the low bit set.
5839 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5840 // cast (X != 0) to int --> X iff X has only the low bit set.
5841 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5842 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5843 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5844 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5845 // If Op1C some other power of two, convert:
5846 uint64_t KnownZero, KnownOne;
5847 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5848 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5849
5850 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5851 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5852 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5853 // (X&4) == 2 --> false
5854 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005855 Constant *Res = ConstantBool::get(isSetNE);
5856 Res = ConstantExpr::getCast(Res, CI.getType());
5857 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005858 }
5859
5860 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5861 Value *In = Op0;
5862 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005863 // Perform an unsigned shr by shiftamt. Convert input to
5864 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005865 if (In->getType()->isSigned())
5866 In = InsertNewInstBefore(new CastInst(In,
5867 In->getType()->getUnsignedVersion(), In->getName()),CI);
5868 // Insert the shift to put the result in the low bit.
5869 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005870 ConstantInt::get(Type::UByteTy, ShiftAmt),
5871 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005872 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005873
5874 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5875 Constant *One = ConstantInt::get(In->getType(), 1);
5876 In = BinaryOperator::createXor(In, One, "tmp");
5877 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005878 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005879
5880 if (CI.getType() == In->getType())
5881 return ReplaceInstUsesWith(CI, In);
5882 else
5883 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005884 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005885 }
5886 }
5887 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005888 }
5889 }
Chris Lattner99155be2006-05-25 23:24:33 +00005890
5891 if (SrcI->hasOneUse()) {
5892 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5893 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5894 // because the inputs are known to be a vector. Check to see if this is
5895 // a cast to a vector with the same # elts.
5896 if (isa<PackedType>(CI.getType()) &&
5897 cast<PackedType>(CI.getType())->getNumElements() ==
5898 SVI->getType()->getNumElements()) {
5899 CastInst *Tmp;
5900 // If either of the operands is a cast from CI.getType(), then
5901 // evaluating the shuffle in the casted destination's type will allow
5902 // us to eliminate at least one cast.
5903 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5904 Tmp->getOperand(0)->getType() == CI.getType()) ||
5905 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005906 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005907 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5908 CI.getType(), &CI);
5909 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5910 CI.getType(), &CI);
5911 // Return a new shuffle vector. Use the same element ID's, as we
5912 // know the vector types match #elts.
5913 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5914 }
5915 }
5916 }
5917 }
5918 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005919
Chris Lattner260ab202002-04-18 17:39:14 +00005920 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005921}
5922
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005923/// GetSelectFoldableOperands - We want to turn code that looks like this:
5924/// %C = or %A, %B
5925/// %D = select %cond, %C, %A
5926/// into:
5927/// %C = select %cond, %B, 0
5928/// %D = or %A, %C
5929///
5930/// Assuming that the specified instruction is an operand to the select, return
5931/// a bitmask indicating which operands of this instruction are foldable if they
5932/// equal the other incoming value of the select.
5933///
5934static unsigned GetSelectFoldableOperands(Instruction *I) {
5935 switch (I->getOpcode()) {
5936 case Instruction::Add:
5937 case Instruction::Mul:
5938 case Instruction::And:
5939 case Instruction::Or:
5940 case Instruction::Xor:
5941 return 3; // Can fold through either operand.
5942 case Instruction::Sub: // Can only fold on the amount subtracted.
5943 case Instruction::Shl: // Can only fold on the shift amount.
5944 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005945 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005946 default:
5947 return 0; // Cannot fold
5948 }
5949}
5950
5951/// GetSelectFoldableConstant - For the same transformation as the previous
5952/// function, return the identity constant that goes into the select.
5953static Constant *GetSelectFoldableConstant(Instruction *I) {
5954 switch (I->getOpcode()) {
5955 default: assert(0 && "This cannot happen!"); abort();
5956 case Instruction::Add:
5957 case Instruction::Sub:
5958 case Instruction::Or:
5959 case Instruction::Xor:
5960 return Constant::getNullValue(I->getType());
5961 case Instruction::Shl:
5962 case Instruction::Shr:
5963 return Constant::getNullValue(Type::UByteTy);
5964 case Instruction::And:
5965 return ConstantInt::getAllOnesValue(I->getType());
5966 case Instruction::Mul:
5967 return ConstantInt::get(I->getType(), 1);
5968 }
5969}
5970
Chris Lattner411336f2005-01-19 21:50:18 +00005971/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5972/// have the same opcode and only one use each. Try to simplify this.
5973Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5974 Instruction *FI) {
5975 if (TI->getNumOperands() == 1) {
5976 // If this is a non-volatile load or a cast from the same type,
5977 // merge.
5978 if (TI->getOpcode() == Instruction::Cast) {
5979 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5980 return 0;
5981 } else {
5982 return 0; // unknown unary op.
5983 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005984
Chris Lattner411336f2005-01-19 21:50:18 +00005985 // Fold this by inserting a select from the input values.
5986 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5987 FI->getOperand(0), SI.getName()+".v");
5988 InsertNewInstBefore(NewSI, SI);
5989 return new CastInst(NewSI, TI->getType());
5990 }
5991
5992 // Only handle binary operators here.
5993 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5994 return 0;
5995
5996 // Figure out if the operations have any operands in common.
5997 Value *MatchOp, *OtherOpT, *OtherOpF;
5998 bool MatchIsOpZero;
5999 if (TI->getOperand(0) == FI->getOperand(0)) {
6000 MatchOp = TI->getOperand(0);
6001 OtherOpT = TI->getOperand(1);
6002 OtherOpF = FI->getOperand(1);
6003 MatchIsOpZero = true;
6004 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6005 MatchOp = TI->getOperand(1);
6006 OtherOpT = TI->getOperand(0);
6007 OtherOpF = FI->getOperand(0);
6008 MatchIsOpZero = false;
6009 } else if (!TI->isCommutative()) {
6010 return 0;
6011 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6012 MatchOp = TI->getOperand(0);
6013 OtherOpT = TI->getOperand(1);
6014 OtherOpF = FI->getOperand(0);
6015 MatchIsOpZero = true;
6016 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6017 MatchOp = TI->getOperand(1);
6018 OtherOpT = TI->getOperand(0);
6019 OtherOpF = FI->getOperand(1);
6020 MatchIsOpZero = true;
6021 } else {
6022 return 0;
6023 }
6024
6025 // If we reach here, they do have operations in common.
6026 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6027 OtherOpF, SI.getName()+".v");
6028 InsertNewInstBefore(NewSI, SI);
6029
6030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6031 if (MatchIsOpZero)
6032 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6033 else
6034 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6035 } else {
6036 if (MatchIsOpZero)
6037 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6038 else
6039 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6040 }
6041}
6042
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006043Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006044 Value *CondVal = SI.getCondition();
6045 Value *TrueVal = SI.getTrueValue();
6046 Value *FalseVal = SI.getFalseValue();
6047
6048 // select true, X, Y -> X
6049 // select false, X, Y -> Y
6050 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006051 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006052
6053 // select C, X, X -> X
6054 if (TrueVal == FalseVal)
6055 return ReplaceInstUsesWith(SI, TrueVal);
6056
Chris Lattner81a7a232004-10-16 18:11:37 +00006057 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6058 return ReplaceInstUsesWith(SI, FalseVal);
6059 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6060 return ReplaceInstUsesWith(SI, TrueVal);
6061 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6062 if (isa<Constant>(TrueVal))
6063 return ReplaceInstUsesWith(SI, TrueVal);
6064 else
6065 return ReplaceInstUsesWith(SI, FalseVal);
6066 }
6067
Chris Lattner1c631e82004-04-08 04:43:23 +00006068 if (SI.getType() == Type::BoolTy)
6069 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006070 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006071 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006072 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006073 } else {
6074 // Change: A = select B, false, C --> A = and !B, C
6075 Value *NotCond =
6076 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6077 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006078 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006079 }
6080 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006081 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006082 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006083 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006084 } else {
6085 // Change: A = select B, C, true --> A = or !B, C
6086 Value *NotCond =
6087 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6088 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006089 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006090 }
6091 }
6092
Chris Lattner183b3362004-04-09 19:05:30 +00006093 // Selecting between two integer constants?
6094 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6095 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6096 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006097 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006098 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006099 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006100 // select C, 0, 1 -> cast !C to int
6101 Value *NotCond =
6102 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006103 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006104 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006105 }
Chris Lattner35167c32004-06-09 07:59:58 +00006106
Chris Lattner380c7e92006-09-20 04:44:59 +00006107 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6108
6109 // (x <s 0) ? -1 : 0 -> sra x, 31
6110 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6111 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6112 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6113 bool CanXForm = false;
6114 if (CmpCst->getType()->isSigned())
6115 CanXForm = CmpCst->isNullValue() &&
6116 IC->getOpcode() == Instruction::SetLT;
6117 else {
6118 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006119 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006120 IC->getOpcode() == Instruction::SetGT;
6121 }
6122
6123 if (CanXForm) {
6124 // The comparison constant and the result are not neccessarily the
6125 // same width. In any case, the first step to do is make sure
6126 // that X is signed.
6127 Value *X = IC->getOperand(0);
6128 if (!X->getType()->isSigned())
6129 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6130
6131 // Now that X is signed, we have to make the all ones value. Do
6132 // this by inserting a new SRA.
6133 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006134 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Chris Lattner380c7e92006-09-20 04:44:59 +00006135 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6136 ShAmt, "ones");
6137 InsertNewInstBefore(SRA, SI);
6138
6139 // Finally, convert to the type of the select RHS. If this is
6140 // smaller than the compare value, it will truncate the ones to
6141 // fit. If it is larger, it will sext the ones to fit.
6142 return new CastInst(SRA, SI.getType());
6143 }
6144 }
6145
6146
6147 // If one of the constants is zero (we know they can't both be) and we
6148 // have a setcc instruction with zero, and we have an 'and' with the
6149 // non-constant value, eliminate this whole mess. This corresponds to
6150 // cases like this: ((X & 27) ? 27 : 0)
6151 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006152 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006153 cast<Constant>(IC->getOperand(1))->isNullValue())
6154 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6155 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006156 isa<ConstantInt>(ICA->getOperand(1)) &&
6157 (ICA->getOperand(1) == TrueValC ||
6158 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006159 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6160 // Okay, now we know that everything is set up, we just don't
6161 // know whether we have a setne or seteq and whether the true or
6162 // false val is the zero.
6163 bool ShouldNotVal = !TrueValC->isNullValue();
6164 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6165 Value *V = ICA;
6166 if (ShouldNotVal)
6167 V = InsertNewInstBefore(BinaryOperator::create(
6168 Instruction::Xor, V, ICA->getOperand(1)), SI);
6169 return ReplaceInstUsesWith(SI, V);
6170 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006171 }
Chris Lattner533bc492004-03-30 19:37:13 +00006172 }
Chris Lattner623fba12004-04-10 22:21:27 +00006173
6174 // See if we are selecting two values based on a comparison of the two values.
6175 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6176 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6177 // Transform (X == Y) ? X : Y -> Y
6178 if (SCI->getOpcode() == Instruction::SetEQ)
6179 return ReplaceInstUsesWith(SI, FalseVal);
6180 // Transform (X != Y) ? X : Y -> X
6181 if (SCI->getOpcode() == Instruction::SetNE)
6182 return ReplaceInstUsesWith(SI, TrueVal);
6183 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6184
6185 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6186 // Transform (X == Y) ? Y : X -> X
6187 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006188 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006189 // Transform (X != Y) ? Y : X -> Y
6190 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006191 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006192 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6193 }
6194 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006195
Chris Lattnera04c9042005-01-13 22:52:24 +00006196 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6197 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6198 if (TI->hasOneUse() && FI->hasOneUse()) {
6199 bool isInverse = false;
6200 Instruction *AddOp = 0, *SubOp = 0;
6201
Chris Lattner411336f2005-01-19 21:50:18 +00006202 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6203 if (TI->getOpcode() == FI->getOpcode())
6204 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6205 return IV;
6206
6207 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6208 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006209 if (TI->getOpcode() == Instruction::Sub &&
6210 FI->getOpcode() == Instruction::Add) {
6211 AddOp = FI; SubOp = TI;
6212 } else if (FI->getOpcode() == Instruction::Sub &&
6213 TI->getOpcode() == Instruction::Add) {
6214 AddOp = TI; SubOp = FI;
6215 }
6216
6217 if (AddOp) {
6218 Value *OtherAddOp = 0;
6219 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6220 OtherAddOp = AddOp->getOperand(1);
6221 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6222 OtherAddOp = AddOp->getOperand(0);
6223 }
6224
6225 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006226 // So at this point we know we have (Y -> OtherAddOp):
6227 // select C, (add X, Y), (sub X, Z)
6228 Value *NegVal; // Compute -Z
6229 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6230 NegVal = ConstantExpr::getNeg(C);
6231 } else {
6232 NegVal = InsertNewInstBefore(
6233 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006234 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006235
6236 Value *NewTrueOp = OtherAddOp;
6237 Value *NewFalseOp = NegVal;
6238 if (AddOp != TI)
6239 std::swap(NewTrueOp, NewFalseOp);
6240 Instruction *NewSel =
6241 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6242
6243 NewSel = InsertNewInstBefore(NewSel, SI);
6244 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006245 }
6246 }
6247 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006248
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006249 // See if we can fold the select into one of our operands.
6250 if (SI.getType()->isInteger()) {
6251 // See the comment above GetSelectFoldableOperands for a description of the
6252 // transformation we are doing here.
6253 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6254 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6255 !isa<Constant>(FalseVal))
6256 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6257 unsigned OpToFold = 0;
6258 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6259 OpToFold = 1;
6260 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6261 OpToFold = 2;
6262 }
6263
6264 if (OpToFold) {
6265 Constant *C = GetSelectFoldableConstant(TVI);
6266 std::string Name = TVI->getName(); TVI->setName("");
6267 Instruction *NewSel =
6268 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6269 Name);
6270 InsertNewInstBefore(NewSel, SI);
6271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6272 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6273 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6274 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6275 else {
6276 assert(0 && "Unknown instruction!!");
6277 }
6278 }
6279 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006280
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006281 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6282 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6283 !isa<Constant>(TrueVal))
6284 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6285 unsigned OpToFold = 0;
6286 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6287 OpToFold = 1;
6288 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6289 OpToFold = 2;
6290 }
6291
6292 if (OpToFold) {
6293 Constant *C = GetSelectFoldableConstant(FVI);
6294 std::string Name = FVI->getName(); FVI->setName("");
6295 Instruction *NewSel =
6296 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6297 Name);
6298 InsertNewInstBefore(NewSel, SI);
6299 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6300 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6301 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6302 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6303 else {
6304 assert(0 && "Unknown instruction!!");
6305 }
6306 }
6307 }
6308 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006309
6310 if (BinaryOperator::isNot(CondVal)) {
6311 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6312 SI.setOperand(1, FalseVal);
6313 SI.setOperand(2, TrueVal);
6314 return &SI;
6315 }
6316
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006317 return 0;
6318}
6319
Chris Lattner82f2ef22006-03-06 20:18:44 +00006320/// GetKnownAlignment - If the specified pointer has an alignment that we can
6321/// determine, return it, otherwise return 0.
6322static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6323 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6324 unsigned Align = GV->getAlignment();
6325 if (Align == 0 && TD)
6326 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6327 return Align;
6328 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6329 unsigned Align = AI->getAlignment();
6330 if (Align == 0 && TD) {
6331 if (isa<AllocaInst>(AI))
6332 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6333 else if (isa<MallocInst>(AI)) {
6334 // Malloc returns maximally aligned memory.
6335 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6336 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6337 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6338 }
6339 }
6340 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006341 } else if (isa<CastInst>(V) ||
6342 (isa<ConstantExpr>(V) &&
6343 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6344 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006345 if (isa<PointerType>(CI->getOperand(0)->getType()))
6346 return GetKnownAlignment(CI->getOperand(0), TD);
6347 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006348 } else if (isa<GetElementPtrInst>(V) ||
6349 (isa<ConstantExpr>(V) &&
6350 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6351 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006352 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6353 if (BaseAlignment == 0) return 0;
6354
6355 // If all indexes are zero, it is just the alignment of the base pointer.
6356 bool AllZeroOperands = true;
6357 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6358 if (!isa<Constant>(GEPI->getOperand(i)) ||
6359 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6360 AllZeroOperands = false;
6361 break;
6362 }
6363 if (AllZeroOperands)
6364 return BaseAlignment;
6365
6366 // Otherwise, if the base alignment is >= the alignment we expect for the
6367 // base pointer type, then we know that the resultant pointer is aligned at
6368 // least as much as its type requires.
6369 if (!TD) return 0;
6370
6371 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6372 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006373 <= BaseAlignment) {
6374 const Type *GEPTy = GEPI->getType();
6375 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6376 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006377 return 0;
6378 }
6379 return 0;
6380}
6381
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006382
Chris Lattnerc66b2232006-01-13 20:11:04 +00006383/// visitCallInst - CallInst simplification. This mostly only handles folding
6384/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6385/// the heavy lifting.
6386///
Chris Lattner970c33a2003-06-19 17:00:31 +00006387Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006388 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6389 if (!II) return visitCallSite(&CI);
6390
Chris Lattner51ea1272004-02-28 05:22:00 +00006391 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6392 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006393 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006394 bool Changed = false;
6395
6396 // memmove/cpy/set of zero bytes is a noop.
6397 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6398 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6399
Chris Lattner00648e12004-10-12 04:52:52 +00006400 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006401 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006402 // Replace the instruction with just byte operations. We would
6403 // transform other cases to loads/stores, but we don't know if
6404 // alignment is sufficient.
6405 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006406 }
6407
Chris Lattner00648e12004-10-12 04:52:52 +00006408 // If we have a memmove and the source operation is a constant global,
6409 // then the source and dest pointers can't alias, so we can change this
6410 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006411 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006412 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6413 if (GVSrc->isConstant()) {
6414 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006415 const char *Name;
6416 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6417 Type::UIntTy)
6418 Name = "llvm.memcpy.i32";
6419 else
6420 Name = "llvm.memcpy.i64";
6421 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006422 CI.getCalledFunction()->getFunctionType());
6423 CI.setOperand(0, MemCpy);
6424 Changed = true;
6425 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006426 }
Chris Lattner00648e12004-10-12 04:52:52 +00006427
Chris Lattner82f2ef22006-03-06 20:18:44 +00006428 // If we can determine a pointer alignment that is bigger than currently
6429 // set, update the alignment.
6430 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6431 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6432 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6433 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006434 if (MI->getAlignment()->getZExtValue() < Align) {
6435 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006436 Changed = true;
6437 }
6438 } else if (isa<MemSetInst>(MI)) {
6439 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006440 if (MI->getAlignment()->getZExtValue() < Alignment) {
6441 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006442 Changed = true;
6443 }
6444 }
6445
Chris Lattnerc66b2232006-01-13 20:11:04 +00006446 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006447 } else {
6448 switch (II->getIntrinsicID()) {
6449 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006450 case Intrinsic::ppc_altivec_lvx:
6451 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006452 case Intrinsic::x86_sse_loadu_ps:
6453 case Intrinsic::x86_sse2_loadu_pd:
6454 case Intrinsic::x86_sse2_loadu_dq:
6455 // Turn PPC lvx -> load if the pointer is known aligned.
6456 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006457 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006458 Value *Ptr = InsertCastBefore(II->getOperand(1),
6459 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006460 return new LoadInst(Ptr);
6461 }
6462 break;
6463 case Intrinsic::ppc_altivec_stvx:
6464 case Intrinsic::ppc_altivec_stvxl:
6465 // Turn stvx -> store if the pointer is known aligned.
6466 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006467 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6468 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006469 return new StoreInst(II->getOperand(1), Ptr);
6470 }
6471 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006472 case Intrinsic::x86_sse_storeu_ps:
6473 case Intrinsic::x86_sse2_storeu_pd:
6474 case Intrinsic::x86_sse2_storeu_dq:
6475 case Intrinsic::x86_sse2_storel_dq:
6476 // Turn X86 storeu -> store if the pointer is known aligned.
6477 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6478 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6479 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6480 return new StoreInst(II->getOperand(2), Ptr);
6481 }
6482 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006483
6484 case Intrinsic::x86_sse_cvttss2si: {
6485 // These intrinsics only demands the 0th element of its input vector. If
6486 // we can simplify the input based on that, do so now.
6487 uint64_t UndefElts;
6488 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6489 UndefElts)) {
6490 II->setOperand(1, V);
6491 return II;
6492 }
6493 break;
6494 }
6495
Chris Lattnere79d2492006-04-06 19:19:17 +00006496 case Intrinsic::ppc_altivec_vperm:
6497 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6498 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6499 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6500
6501 // Check that all of the elements are integer constants or undefs.
6502 bool AllEltsOk = true;
6503 for (unsigned i = 0; i != 16; ++i) {
6504 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6505 !isa<UndefValue>(Mask->getOperand(i))) {
6506 AllEltsOk = false;
6507 break;
6508 }
6509 }
6510
6511 if (AllEltsOk) {
6512 // Cast the input vectors to byte vectors.
6513 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6514 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6515 Value *Result = UndefValue::get(Op0->getType());
6516
6517 // Only extract each element once.
6518 Value *ExtractedElts[32];
6519 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6520
6521 for (unsigned i = 0; i != 16; ++i) {
6522 if (isa<UndefValue>(Mask->getOperand(i)))
6523 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006524 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006525 Idx &= 31; // Match the hardware behavior.
6526
6527 if (ExtractedElts[Idx] == 0) {
6528 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006529 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006530 InsertNewInstBefore(Elt, CI);
6531 ExtractedElts[Idx] = Elt;
6532 }
6533
6534 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006535 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006536 InsertNewInstBefore(cast<Instruction>(Result), CI);
6537 }
6538 return new CastInst(Result, CI.getType());
6539 }
6540 }
6541 break;
6542
Chris Lattner503221f2006-01-13 21:28:09 +00006543 case Intrinsic::stackrestore: {
6544 // If the save is right next to the restore, remove the restore. This can
6545 // happen when variable allocas are DCE'd.
6546 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6547 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6548 BasicBlock::iterator BI = SS;
6549 if (&*++BI == II)
6550 return EraseInstFromFunction(CI);
6551 }
6552 }
6553
6554 // If the stack restore is in a return/unwind block and if there are no
6555 // allocas or calls between the restore and the return, nuke the restore.
6556 TerminatorInst *TI = II->getParent()->getTerminator();
6557 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6558 BasicBlock::iterator BI = II;
6559 bool CannotRemove = false;
6560 for (++BI; &*BI != TI; ++BI) {
6561 if (isa<AllocaInst>(BI) ||
6562 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6563 CannotRemove = true;
6564 break;
6565 }
6566 }
6567 if (!CannotRemove)
6568 return EraseInstFromFunction(CI);
6569 }
6570 break;
6571 }
6572 }
Chris Lattner00648e12004-10-12 04:52:52 +00006573 }
6574
Chris Lattnerc66b2232006-01-13 20:11:04 +00006575 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006576}
6577
6578// InvokeInst simplification
6579//
6580Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006581 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006582}
6583
Chris Lattneraec3d942003-10-07 22:32:43 +00006584// visitCallSite - Improvements for call and invoke instructions.
6585//
6586Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006587 bool Changed = false;
6588
6589 // If the callee is a constexpr cast of a function, attempt to move the cast
6590 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006591 if (transformConstExprCastCall(CS)) return 0;
6592
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006593 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006594
Chris Lattner61d9d812005-05-13 07:09:09 +00006595 if (Function *CalleeF = dyn_cast<Function>(Callee))
6596 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6597 Instruction *OldCall = CS.getInstruction();
6598 // If the call and callee calling conventions don't match, this call must
6599 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006600 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006601 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6602 if (!OldCall->use_empty())
6603 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6604 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6605 return EraseInstFromFunction(*OldCall);
6606 return 0;
6607 }
6608
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006609 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6610 // This instruction is not reachable, just remove it. We insert a store to
6611 // undef so that we know that this code is not reachable, despite the fact
6612 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006613 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006614 UndefValue::get(PointerType::get(Type::BoolTy)),
6615 CS.getInstruction());
6616
6617 if (!CS.getInstruction()->use_empty())
6618 CS.getInstruction()->
6619 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6620
6621 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6622 // Don't break the CFG, insert a dummy cond branch.
6623 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006624 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006625 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006626 return EraseInstFromFunction(*CS.getInstruction());
6627 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006628
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006629 const PointerType *PTy = cast<PointerType>(Callee->getType());
6630 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6631 if (FTy->isVarArg()) {
6632 // See if we can optimize any arguments passed through the varargs area of
6633 // the call.
6634 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6635 E = CS.arg_end(); I != E; ++I)
6636 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6637 // If this cast does not effect the value passed through the varargs
6638 // area, we can eliminate the use of the cast.
6639 Value *Op = CI->getOperand(0);
6640 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6641 *I = Op;
6642 Changed = true;
6643 }
6644 }
6645 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006646
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006647 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006648}
6649
Chris Lattner970c33a2003-06-19 17:00:31 +00006650// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6651// attempt to move the cast to the arguments of the call/invoke.
6652//
6653bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6654 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6655 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006656 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006657 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006658 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006659 Instruction *Caller = CS.getInstruction();
6660
6661 // Okay, this is a cast from a function to a different type. Unless doing so
6662 // would cause a type conversion of one of our arguments, change this call to
6663 // be a direct call with arguments casted to the appropriate types.
6664 //
6665 const FunctionType *FT = Callee->getFunctionType();
6666 const Type *OldRetTy = Caller->getType();
6667
Chris Lattner1f7942f2004-01-14 06:06:08 +00006668 // Check to see if we are changing the return type...
6669 if (OldRetTy != FT->getReturnType()) {
6670 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006671 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6672 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006673 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006674 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006675 return false; // Cannot transform this return value...
6676
6677 // If the callsite is an invoke instruction, and the return value is used by
6678 // a PHI node in a successor, we cannot change the return type of the call
6679 // because there is no place to put the cast instruction (without breaking
6680 // the critical edge). Bail out in this case.
6681 if (!Caller->use_empty())
6682 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6683 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6684 UI != E; ++UI)
6685 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6686 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006687 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006688 return false;
6689 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006690
6691 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6692 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006693
Chris Lattner970c33a2003-06-19 17:00:31 +00006694 CallSite::arg_iterator AI = CS.arg_begin();
6695 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6696 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006697 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006698 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006699 //Either we can cast directly, or we can upconvert the argument
6700 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6701 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6702 ParamTy->isSigned() == ActTy->isSigned() &&
6703 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6704 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006705 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006706 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006707 }
6708
6709 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6710 Callee->isExternal())
6711 return false; // Do not delete arguments unless we have a function body...
6712
6713 // Okay, we decided that this is a safe thing to do: go ahead and start
6714 // inserting cast instructions as necessary...
6715 std::vector<Value*> Args;
6716 Args.reserve(NumActualArgs);
6717
6718 AI = CS.arg_begin();
6719 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6720 const Type *ParamTy = FT->getParamType(i);
6721 if ((*AI)->getType() == ParamTy) {
6722 Args.push_back(*AI);
6723 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006724 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6725 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006726 }
6727 }
6728
6729 // If the function takes more arguments than the call was taking, add them
6730 // now...
6731 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6732 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6733
6734 // If we are removing arguments to the function, emit an obnoxious warning...
6735 if (FT->getNumParams() < NumActualArgs)
6736 if (!FT->isVarArg()) {
6737 std::cerr << "WARNING: While resolving call to function '"
6738 << Callee->getName() << "' arguments were dropped!\n";
6739 } else {
6740 // Add all of the arguments in their promoted form to the arg list...
6741 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6742 const Type *PTy = getPromotedType((*AI)->getType());
6743 if (PTy != (*AI)->getType()) {
6744 // Must promote to pass through va_arg area!
6745 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6746 InsertNewInstBefore(Cast, *Caller);
6747 Args.push_back(Cast);
6748 } else {
6749 Args.push_back(*AI);
6750 }
6751 }
6752 }
6753
6754 if (FT->getReturnType() == Type::VoidTy)
6755 Caller->setName(""); // Void type should not have a name...
6756
6757 Instruction *NC;
6758 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006759 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006760 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006761 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006762 } else {
6763 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006764 if (cast<CallInst>(Caller)->isTailCall())
6765 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006766 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006767 }
6768
6769 // Insert a cast of the return type as necessary...
6770 Value *NV = NC;
6771 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6772 if (NV->getType() != Type::VoidTy) {
6773 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006774
6775 // If this is an invoke instruction, we should insert it after the first
6776 // non-phi, instruction in the normal successor block.
6777 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6778 BasicBlock::iterator I = II->getNormalDest()->begin();
6779 while (isa<PHINode>(I)) ++I;
6780 InsertNewInstBefore(NC, *I);
6781 } else {
6782 // Otherwise, it's a call, just insert cast right after the call instr
6783 InsertNewInstBefore(NC, *Caller);
6784 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006785 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006786 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006787 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006788 }
6789 }
6790
6791 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6792 Caller->replaceAllUsesWith(NV);
6793 Caller->getParent()->getInstList().erase(Caller);
6794 removeFromWorkList(Caller);
6795 return true;
6796}
6797
6798
Chris Lattner7515cab2004-11-14 19:13:23 +00006799// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6800// operator and they all are only used by the PHI, PHI together their
6801// inputs, and do the operation once, to the result of the PHI.
6802Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6803 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6804
6805 // Scan the instruction, looking for input operations that can be folded away.
6806 // If all input operands to the phi are the same instruction (e.g. a cast from
6807 // the same type or "+42") we can pull the operation through the PHI, reducing
6808 // code size and simplifying code.
6809 Constant *ConstantOp = 0;
6810 const Type *CastSrcTy = 0;
6811 if (isa<CastInst>(FirstInst)) {
6812 CastSrcTy = FirstInst->getOperand(0)->getType();
6813 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6814 // Can fold binop or shift if the RHS is a constant.
6815 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6816 if (ConstantOp == 0) return 0;
6817 } else {
6818 return 0; // Cannot fold this operation.
6819 }
6820
6821 // Check to see if all arguments are the same operation.
6822 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6823 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6824 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6825 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6826 return 0;
6827 if (CastSrcTy) {
6828 if (I->getOperand(0)->getType() != CastSrcTy)
6829 return 0; // Cast operation must match.
6830 } else if (I->getOperand(1) != ConstantOp) {
6831 return 0;
6832 }
6833 }
6834
6835 // Okay, they are all the same operation. Create a new PHI node of the
6836 // correct type, and PHI together all of the LHS's of the instructions.
6837 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6838 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006839 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006840
6841 Value *InVal = FirstInst->getOperand(0);
6842 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006843
6844 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006845 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6846 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6847 if (NewInVal != InVal)
6848 InVal = 0;
6849 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6850 }
6851
6852 Value *PhiVal;
6853 if (InVal) {
6854 // The new PHI unions all of the same values together. This is really
6855 // common, so we handle it intelligently here for compile-time speed.
6856 PhiVal = InVal;
6857 delete NewPN;
6858 } else {
6859 InsertNewInstBefore(NewPN, PN);
6860 PhiVal = NewPN;
6861 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006862
Chris Lattner7515cab2004-11-14 19:13:23 +00006863 // Insert and return the new operation.
6864 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006865 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006866 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006867 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006868 else
6869 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006870 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006871}
Chris Lattner48a44f72002-05-02 17:06:02 +00006872
Chris Lattner71536432005-01-17 05:10:15 +00006873/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6874/// that is dead.
6875static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6876 if (PN->use_empty()) return true;
6877 if (!PN->hasOneUse()) return false;
6878
6879 // Remember this node, and if we find the cycle, return.
6880 if (!PotentiallyDeadPHIs.insert(PN).second)
6881 return true;
6882
6883 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6884 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006885
Chris Lattner71536432005-01-17 05:10:15 +00006886 return false;
6887}
6888
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006889// PHINode simplification
6890//
Chris Lattner113f4f42002-06-25 16:13:24 +00006891Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006892 // If LCSSA is around, don't mess with Phi nodes
6893 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006894
Owen Andersonae8aa642006-07-10 22:03:18 +00006895 if (Value *V = PN.hasConstantValue())
6896 return ReplaceInstUsesWith(PN, V);
6897
6898 // If the only user of this instruction is a cast instruction, and all of the
6899 // incoming values are constants, change this PHI to merge together the casted
6900 // constants.
6901 if (PN.hasOneUse())
6902 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6903 if (CI->getType() != PN.getType()) { // noop casts will be folded
6904 bool AllConstant = true;
6905 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6906 if (!isa<Constant>(PN.getIncomingValue(i))) {
6907 AllConstant = false;
6908 break;
6909 }
6910 if (AllConstant) {
6911 // Make a new PHI with all casted values.
6912 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6913 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6914 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6915 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6916 PN.getIncomingBlock(i));
6917 }
6918
6919 // Update the cast instruction.
6920 CI->setOperand(0, New);
6921 WorkList.push_back(CI); // revisit the cast instruction to fold.
6922 WorkList.push_back(New); // Make sure to revisit the new Phi
6923 return &PN; // PN is now dead!
6924 }
6925 }
6926
6927 // If all PHI operands are the same operation, pull them through the PHI,
6928 // reducing code size.
6929 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6930 PN.getIncomingValue(0)->hasOneUse())
6931 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6932 return Result;
6933
6934 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6935 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6936 // PHI)... break the cycle.
6937 if (PN.hasOneUse())
6938 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6939 std::set<PHINode*> PotentiallyDeadPHIs;
6940 PotentiallyDeadPHIs.insert(&PN);
6941 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6942 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6943 }
6944
Chris Lattner91daeb52003-12-19 05:58:40 +00006945 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006946}
6947
Chris Lattner69193f92004-04-05 01:30:19 +00006948static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6949 Instruction *InsertPoint,
6950 InstCombiner *IC) {
6951 unsigned PS = IC->getTargetData().getPointerSize();
6952 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006953 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6954 // We must insert a cast to ensure we sign-extend.
6955 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6956 V->getName()), *InsertPoint);
6957 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6958 *InsertPoint);
6959}
6960
Chris Lattner48a44f72002-05-02 17:06:02 +00006961
Chris Lattner113f4f42002-06-25 16:13:24 +00006962Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006963 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006964 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006965 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006966 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006967 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006968
Chris Lattner81a7a232004-10-16 18:11:37 +00006969 if (isa<UndefValue>(GEP.getOperand(0)))
6970 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6971
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006972 bool HasZeroPointerIndex = false;
6973 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6974 HasZeroPointerIndex = C->isNullValue();
6975
6976 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006977 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006978
Chris Lattner69193f92004-04-05 01:30:19 +00006979 // Eliminate unneeded casts for indices.
6980 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006981 gep_type_iterator GTI = gep_type_begin(GEP);
6982 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6983 if (isa<SequentialType>(*GTI)) {
6984 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6985 Value *Src = CI->getOperand(0);
6986 const Type *SrcTy = Src->getType();
6987 const Type *DestTy = CI->getType();
6988 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006989 if (SrcTy->getPrimitiveSizeInBits() ==
6990 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006991 // We can always eliminate a cast from ulong or long to the other.
6992 // We can always eliminate a cast from uint to int or the other on
6993 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006994 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006995 MadeChange = true;
6996 GEP.setOperand(i, Src);
6997 }
6998 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6999 SrcTy->getPrimitiveSize() == 4) {
7000 // We can always eliminate a cast from int to [u]long. We can
7001 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7002 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007003 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007004 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007005 MadeChange = true;
7006 GEP.setOperand(i, Src);
7007 }
Chris Lattner69193f92004-04-05 01:30:19 +00007008 }
7009 }
7010 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007011 // If we are using a wider index than needed for this platform, shrink it
7012 // to what we need. If the incoming value needs a cast instruction,
7013 // insert it. This explicit cast can make subsequent optimizations more
7014 // obvious.
7015 Value *Op = GEP.getOperand(i);
7016 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007017 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007018 GEP.setOperand(i, ConstantExpr::getCast(C,
7019 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007020 MadeChange = true;
7021 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007022 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
7023 Op->getName()), GEP);
7024 GEP.setOperand(i, Op);
7025 MadeChange = true;
7026 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007027
7028 // If this is a constant idx, make sure to canonicalize it to be a signed
7029 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007030 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7031 if (CUI->getType()->isUnsigned()) {
7032 GEP.setOperand(i,
7033 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7034 MadeChange = true;
7035 }
Chris Lattner69193f92004-04-05 01:30:19 +00007036 }
7037 if (MadeChange) return &GEP;
7038
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007039 // Combine Indices - If the source pointer to this getelementptr instruction
7040 // is a getelementptr instruction, combine the indices of the two
7041 // getelementptr instructions into a single instruction.
7042 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007043 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007044 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007045 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007046
7047 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007048 // Note that if our source is a gep chain itself that we wait for that
7049 // chain to be resolved before we perform this transformation. This
7050 // avoids us creating a TON of code in some cases.
7051 //
7052 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7053 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7054 return 0; // Wait until our source is folded to completion.
7055
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007056 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007057
7058 // Find out whether the last index in the source GEP is a sequential idx.
7059 bool EndsWithSequential = false;
7060 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7061 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007062 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007063
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007064 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007065 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007066 // Replace: gep (gep %P, long B), long A, ...
7067 // With: T = long A+B; gep %P, T, ...
7068 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007069 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007070 if (SO1 == Constant::getNullValue(SO1->getType())) {
7071 Sum = GO1;
7072 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7073 Sum = SO1;
7074 } else {
7075 // If they aren't the same type, convert both to an integer of the
7076 // target's pointer size.
7077 if (SO1->getType() != GO1->getType()) {
7078 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7079 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7080 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7081 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7082 } else {
7083 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007084 if (SO1->getType()->getPrimitiveSize() == PS) {
7085 // Convert GO1 to SO1's type.
7086 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7087
7088 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7089 // Convert SO1 to GO1's type.
7090 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7091 } else {
7092 const Type *PT = TD->getIntPtrType();
7093 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7094 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7095 }
7096 }
7097 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007098 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7099 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7100 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007101 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7102 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007103 }
Chris Lattner69193f92004-04-05 01:30:19 +00007104 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007105
7106 // Recycle the GEP we already have if possible.
7107 if (SrcGEPOperands.size() == 2) {
7108 GEP.setOperand(0, SrcGEPOperands[0]);
7109 GEP.setOperand(1, Sum);
7110 return &GEP;
7111 } else {
7112 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7113 SrcGEPOperands.end()-1);
7114 Indices.push_back(Sum);
7115 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7116 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007117 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007118 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007119 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007120 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007121 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7122 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007123 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7124 }
7125
7126 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007127 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007128
Chris Lattner5f667a62004-05-07 22:09:22 +00007129 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007130 // GEP of global variable. If all of the indices for this GEP are
7131 // constants, we can promote this to a constexpr instead of an instruction.
7132
7133 // Scan for nonconstants...
7134 std::vector<Constant*> Indices;
7135 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7136 for (; I != E && isa<Constant>(*I); ++I)
7137 Indices.push_back(cast<Constant>(*I));
7138
7139 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007140 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007141
7142 // Replace all uses of the GEP with the new constexpr...
7143 return ReplaceInstUsesWith(GEP, CE);
7144 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007145 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7146 if (!isa<PointerType>(X->getType())) {
7147 // Not interesting. Source pointer must be a cast from pointer.
7148 } else if (HasZeroPointerIndex) {
7149 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7150 // into : GEP [10 x ubyte]* X, long 0, ...
7151 //
7152 // This occurs when the program declares an array extern like "int X[];"
7153 //
7154 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7155 const PointerType *XTy = cast<PointerType>(X->getType());
7156 if (const ArrayType *XATy =
7157 dyn_cast<ArrayType>(XTy->getElementType()))
7158 if (const ArrayType *CATy =
7159 dyn_cast<ArrayType>(CPTy->getElementType()))
7160 if (CATy->getElementType() == XATy->getElementType()) {
7161 // At this point, we know that the cast source type is a pointer
7162 // to an array of the same type as the destination pointer
7163 // array. Because the array type is never stepped over (there
7164 // is a leading zero) we can fold the cast into this GEP.
7165 GEP.setOperand(0, X);
7166 return &GEP;
7167 }
7168 } else if (GEP.getNumOperands() == 2) {
7169 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007170 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7171 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007172 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7173 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7174 if (isa<ArrayType>(SrcElTy) &&
7175 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7176 TD->getTypeSize(ResElTy)) {
7177 Value *V = InsertNewInstBefore(
7178 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7179 GEP.getOperand(1), GEP.getName()), GEP);
7180 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007181 }
Chris Lattner2a893292005-09-13 18:36:04 +00007182
7183 // Transform things like:
7184 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7185 // (where tmp = 8*tmp2) into:
7186 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7187
7188 if (isa<ArrayType>(SrcElTy) &&
7189 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7190 uint64_t ArrayEltSize =
7191 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7192
7193 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7194 // allow either a mul, shift, or constant here.
7195 Value *NewIdx = 0;
7196 ConstantInt *Scale = 0;
7197 if (ArrayEltSize == 1) {
7198 NewIdx = GEP.getOperand(1);
7199 Scale = ConstantInt::get(NewIdx->getType(), 1);
7200 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007201 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007202 Scale = CI;
7203 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7204 if (Inst->getOpcode() == Instruction::Shl &&
7205 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007206 unsigned ShAmt =
7207 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007208 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007209 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007210 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007211 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007212 NewIdx = Inst->getOperand(0);
7213 } else if (Inst->getOpcode() == Instruction::Mul &&
7214 isa<ConstantInt>(Inst->getOperand(1))) {
7215 Scale = cast<ConstantInt>(Inst->getOperand(1));
7216 NewIdx = Inst->getOperand(0);
7217 }
7218 }
7219
7220 // If the index will be to exactly the right offset with the scale taken
7221 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007222 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7223 if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7224 Scale = ConstantInt::get(Scale->getType(),
7225 Scale->getZExtValue() / ArrayEltSize);
7226 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007227 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7228 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7229 NewIdx = InsertNewInstBefore(Sc, GEP);
7230 }
7231
7232 // Insert the new GEP instruction.
7233 Instruction *Idx =
7234 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7235 NewIdx, GEP.getName());
7236 Idx = InsertNewInstBefore(Idx, GEP);
7237 return new CastInst(Idx, GEP.getType());
7238 }
7239 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007240 }
Chris Lattnerca081252001-12-14 16:52:21 +00007241 }
7242
Chris Lattnerca081252001-12-14 16:52:21 +00007243 return 0;
7244}
7245
Chris Lattner1085bdf2002-11-04 16:18:53 +00007246Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7247 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7248 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007249 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7250 const Type *NewTy =
7251 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007252 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007253
7254 // Create and insert the replacement instruction...
7255 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007256 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007257 else {
7258 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007259 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007260 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007261
7262 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007263
Chris Lattner1085bdf2002-11-04 16:18:53 +00007264 // Scan to the end of the allocation instructions, to skip over a block of
7265 // allocas if possible...
7266 //
7267 BasicBlock::iterator It = New;
7268 while (isa<AllocationInst>(*It)) ++It;
7269
7270 // Now that I is pointing to the first non-allocation-inst in the block,
7271 // insert our getelementptr instruction...
7272 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007273 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7274 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7275 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007276
7277 // Now make everything use the getelementptr instead of the original
7278 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007279 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007280 } else if (isa<UndefValue>(AI.getArraySize())) {
7281 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007282 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007283
7284 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7285 // Note that we only do this for alloca's, because malloc should allocate and
7286 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007287 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007288 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007289 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7290
Chris Lattner1085bdf2002-11-04 16:18:53 +00007291 return 0;
7292}
7293
Chris Lattner8427bff2003-12-07 01:24:23 +00007294Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7295 Value *Op = FI.getOperand(0);
7296
7297 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7298 if (CastInst *CI = dyn_cast<CastInst>(Op))
7299 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7300 FI.setOperand(0, CI->getOperand(0));
7301 return &FI;
7302 }
7303
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007304 // free undef -> unreachable.
7305 if (isa<UndefValue>(Op)) {
7306 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007307 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007308 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7309 return EraseInstFromFunction(FI);
7310 }
7311
Chris Lattnerf3a36602004-02-28 04:57:37 +00007312 // If we have 'free null' delete the instruction. This can happen in stl code
7313 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007314 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007315 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007316
Chris Lattner8427bff2003-12-07 01:24:23 +00007317 return 0;
7318}
7319
7320
Chris Lattner72684fe2005-01-31 05:51:45 +00007321/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007322static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7323 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007324 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007325
7326 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007327 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007328 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007329
Chris Lattnerebca4762006-04-02 05:37:12 +00007330 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7331 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007332 // If the source is an array, the code below will not succeed. Check to
7333 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7334 // constants.
7335 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7336 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7337 if (ASrcTy->getNumElements() != 0) {
7338 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7339 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7340 SrcTy = cast<PointerType>(CastOp->getType());
7341 SrcPTy = SrcTy->getElementType();
7342 }
7343
Chris Lattnerebca4762006-04-02 05:37:12 +00007344 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7345 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007346 // Do not allow turning this into a load of an integer, which is then
7347 // casted to a pointer, this pessimizes pointer analysis a lot.
7348 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007349 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007350 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007351
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007352 // Okay, we are casting from one integer or pointer type to another of
7353 // the same size. Instead of casting the pointer before the load, cast
7354 // the result of the loaded value.
7355 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7356 CI->getName(),
7357 LI.isVolatile()),LI);
7358 // Now cast the result of the load.
7359 return new CastInst(NewLoad, LI.getType());
7360 }
Chris Lattner35e24772004-07-13 01:49:43 +00007361 }
7362 }
7363 return 0;
7364}
7365
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007366/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007367/// from this value cannot trap. If it is not obviously safe to load from the
7368/// specified pointer, we do a quick local scan of the basic block containing
7369/// ScanFrom, to determine if the address is already accessed.
7370static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7371 // If it is an alloca or global variable, it is always safe to load from.
7372 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7373
7374 // Otherwise, be a little bit agressive by scanning the local block where we
7375 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007376 // from/to. If so, the previous load or store would have already trapped,
7377 // so there is no harm doing an extra load (also, CSE will later eliminate
7378 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007379 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7380
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007381 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007382 --BBI;
7383
7384 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7385 if (LI->getOperand(0) == V) return true;
7386 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7387 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007388
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007389 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007390 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007391}
7392
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007393Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7394 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007395
Chris Lattnera9d84e32005-05-01 04:24:53 +00007396 // load (cast X) --> cast (load X) iff safe
7397 if (CastInst *CI = dyn_cast<CastInst>(Op))
7398 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7399 return Res;
7400
7401 // None of the following transforms are legal for volatile loads.
7402 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007403
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007404 if (&LI.getParent()->front() != &LI) {
7405 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007406 // If the instruction immediately before this is a store to the same
7407 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007408 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7409 if (SI->getOperand(1) == LI.getOperand(0))
7410 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007411 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7412 if (LIB->getOperand(0) == LI.getOperand(0))
7413 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007414 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007415
7416 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7417 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7418 isa<UndefValue>(GEPI->getOperand(0))) {
7419 // Insert a new store to null instruction before the load to indicate
7420 // that this code is not reachable. We do this instead of inserting
7421 // an unreachable instruction directly because we cannot modify the
7422 // CFG.
7423 new StoreInst(UndefValue::get(LI.getType()),
7424 Constant::getNullValue(Op->getType()), &LI);
7425 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7426 }
7427
Chris Lattner81a7a232004-10-16 18:11:37 +00007428 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007429 // load null/undef -> undef
7430 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007431 // Insert a new store to null instruction before the load to indicate that
7432 // this code is not reachable. We do this instead of inserting an
7433 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007434 new StoreInst(UndefValue::get(LI.getType()),
7435 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007436 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007437 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007438
Chris Lattner81a7a232004-10-16 18:11:37 +00007439 // Instcombine load (constant global) into the value loaded.
7440 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7441 if (GV->isConstant() && !GV->isExternal())
7442 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007443
Chris Lattner81a7a232004-10-16 18:11:37 +00007444 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7446 if (CE->getOpcode() == Instruction::GetElementPtr) {
7447 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7448 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007449 if (Constant *V =
7450 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007451 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007452 if (CE->getOperand(0)->isNullValue()) {
7453 // Insert a new store to null instruction before the load to indicate
7454 // that this code is not reachable. We do this instead of inserting
7455 // an unreachable instruction directly because we cannot modify the
7456 // CFG.
7457 new StoreInst(UndefValue::get(LI.getType()),
7458 Constant::getNullValue(Op->getType()), &LI);
7459 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7460 }
7461
Chris Lattner81a7a232004-10-16 18:11:37 +00007462 } else if (CE->getOpcode() == Instruction::Cast) {
7463 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7464 return Res;
7465 }
7466 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007467
Chris Lattnera9d84e32005-05-01 04:24:53 +00007468 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007469 // Change select and PHI nodes to select values instead of addresses: this
7470 // helps alias analysis out a lot, allows many others simplifications, and
7471 // exposes redundancy in the code.
7472 //
7473 // Note that we cannot do the transformation unless we know that the
7474 // introduced loads cannot trap! Something like this is valid as long as
7475 // the condition is always false: load (select bool %C, int* null, int* %G),
7476 // but it would not be valid if we transformed it to load from null
7477 // unconditionally.
7478 //
7479 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7480 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007481 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7482 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007483 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007484 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007485 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007486 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007487 return new SelectInst(SI->getCondition(), V1, V2);
7488 }
7489
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007490 // load (select (cond, null, P)) -> load P
7491 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7492 if (C->isNullValue()) {
7493 LI.setOperand(0, SI->getOperand(2));
7494 return &LI;
7495 }
7496
7497 // load (select (cond, P, null)) -> load P
7498 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7499 if (C->isNullValue()) {
7500 LI.setOperand(0, SI->getOperand(1));
7501 return &LI;
7502 }
7503
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007504 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7505 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007506 bool Safe = PN->getParent() == LI.getParent();
7507
7508 // Scan all of the instructions between the PHI and the load to make
7509 // sure there are no instructions that might possibly alter the value
7510 // loaded from the PHI.
7511 if (Safe) {
7512 BasicBlock::iterator I = &LI;
7513 for (--I; !isa<PHINode>(I); --I)
7514 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7515 Safe = false;
7516 break;
7517 }
7518 }
7519
7520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007521 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007522 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007523 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007524
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007525 if (Safe) {
7526 // Create the PHI.
7527 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7528 InsertNewInstBefore(NewPN, *PN);
7529 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7530
7531 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7532 BasicBlock *BB = PN->getIncomingBlock(i);
7533 Value *&TheLoad = LoadMap[BB];
7534 if (TheLoad == 0) {
7535 Value *InVal = PN->getIncomingValue(i);
7536 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7537 InVal->getName()+".val"),
7538 *BB->getTerminator());
7539 }
7540 NewPN->addIncoming(TheLoad, BB);
7541 }
7542 return ReplaceInstUsesWith(LI, NewPN);
7543 }
7544 }
7545 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007546 return 0;
7547}
7548
Chris Lattner72684fe2005-01-31 05:51:45 +00007549/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7550/// when possible.
7551static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7552 User *CI = cast<User>(SI.getOperand(1));
7553 Value *CastOp = CI->getOperand(0);
7554
7555 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7556 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7557 const Type *SrcPTy = SrcTy->getElementType();
7558
7559 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7560 // If the source is an array, the code below will not succeed. Check to
7561 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7562 // constants.
7563 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7564 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7565 if (ASrcTy->getNumElements() != 0) {
7566 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7567 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7568 SrcTy = cast<PointerType>(CastOp->getType());
7569 SrcPTy = SrcTy->getElementType();
7570 }
7571
7572 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007573 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007574 IC.getTargetData().getTypeSize(DestPTy)) {
7575
7576 // Okay, we are casting from one integer or pointer type to another of
7577 // the same size. Instead of casting the pointer before the store, cast
7578 // the value to be stored.
7579 Value *NewCast;
7580 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7581 NewCast = ConstantExpr::getCast(C, SrcPTy);
7582 else
7583 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7584 SrcPTy,
7585 SI.getOperand(0)->getName()+".c"), SI);
7586
7587 return new StoreInst(NewCast, CastOp);
7588 }
7589 }
7590 }
7591 return 0;
7592}
7593
Chris Lattner31f486c2005-01-31 05:36:43 +00007594Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7595 Value *Val = SI.getOperand(0);
7596 Value *Ptr = SI.getOperand(1);
7597
7598 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007599 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007600 ++NumCombined;
7601 return 0;
7602 }
7603
Chris Lattner5997cf92006-02-08 03:25:32 +00007604 // Do really simple DSE, to catch cases where there are several consequtive
7605 // stores to the same location, separated by a few arithmetic operations. This
7606 // situation often occurs with bitfield accesses.
7607 BasicBlock::iterator BBI = &SI;
7608 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7609 --ScanInsts) {
7610 --BBI;
7611
7612 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7613 // Prev store isn't volatile, and stores to the same location?
7614 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7615 ++NumDeadStore;
7616 ++BBI;
7617 EraseInstFromFunction(*PrevSI);
7618 continue;
7619 }
7620 break;
7621 }
7622
Chris Lattnerdab43b22006-05-26 19:19:20 +00007623 // If this is a load, we have to stop. However, if the loaded value is from
7624 // the pointer we're loading and is producing the pointer we're storing,
7625 // then *this* store is dead (X = load P; store X -> P).
7626 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7627 if (LI == Val && LI->getOperand(0) == Ptr) {
7628 EraseInstFromFunction(SI);
7629 ++NumCombined;
7630 return 0;
7631 }
7632 // Otherwise, this is a load from some other location. Stores before it
7633 // may not be dead.
7634 break;
7635 }
7636
Chris Lattner5997cf92006-02-08 03:25:32 +00007637 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007638 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007639 break;
7640 }
7641
7642
7643 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007644
7645 // store X, null -> turns into 'unreachable' in SimplifyCFG
7646 if (isa<ConstantPointerNull>(Ptr)) {
7647 if (!isa<UndefValue>(Val)) {
7648 SI.setOperand(0, UndefValue::get(Val->getType()));
7649 if (Instruction *U = dyn_cast<Instruction>(Val))
7650 WorkList.push_back(U); // Dropped a use.
7651 ++NumCombined;
7652 }
7653 return 0; // Do not modify these!
7654 }
7655
7656 // store undef, Ptr -> noop
7657 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007658 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007659 ++NumCombined;
7660 return 0;
7661 }
7662
Chris Lattner72684fe2005-01-31 05:51:45 +00007663 // If the pointer destination is a cast, see if we can fold the cast into the
7664 // source instead.
7665 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7666 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7667 return Res;
7668 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7669 if (CE->getOpcode() == Instruction::Cast)
7670 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7671 return Res;
7672
Chris Lattner219175c2005-09-12 23:23:25 +00007673
7674 // If this store is the last instruction in the basic block, and if the block
7675 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007676 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007677 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7678 if (BI->isUnconditional()) {
7679 // Check to see if the successor block has exactly two incoming edges. If
7680 // so, see if the other predecessor contains a store to the same location.
7681 // if so, insert a PHI node (if needed) and move the stores down.
7682 BasicBlock *Dest = BI->getSuccessor(0);
7683
7684 pred_iterator PI = pred_begin(Dest);
7685 BasicBlock *Other = 0;
7686 if (*PI != BI->getParent())
7687 Other = *PI;
7688 ++PI;
7689 if (PI != pred_end(Dest)) {
7690 if (*PI != BI->getParent())
7691 if (Other)
7692 Other = 0;
7693 else
7694 Other = *PI;
7695 if (++PI != pred_end(Dest))
7696 Other = 0;
7697 }
7698 if (Other) { // If only one other pred...
7699 BBI = Other->getTerminator();
7700 // Make sure this other block ends in an unconditional branch and that
7701 // there is an instruction before the branch.
7702 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7703 BBI != Other->begin()) {
7704 --BBI;
7705 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7706
7707 // If this instruction is a store to the same location.
7708 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7709 // Okay, we know we can perform this transformation. Insert a PHI
7710 // node now if we need it.
7711 Value *MergedVal = OtherStore->getOperand(0);
7712 if (MergedVal != SI.getOperand(0)) {
7713 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7714 PN->reserveOperandSpace(2);
7715 PN->addIncoming(SI.getOperand(0), SI.getParent());
7716 PN->addIncoming(OtherStore->getOperand(0), Other);
7717 MergedVal = InsertNewInstBefore(PN, Dest->front());
7718 }
7719
7720 // Advance to a place where it is safe to insert the new store and
7721 // insert it.
7722 BBI = Dest->begin();
7723 while (isa<PHINode>(BBI)) ++BBI;
7724 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7725 OtherStore->isVolatile()), *BBI);
7726
7727 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007728 EraseInstFromFunction(SI);
7729 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007730 ++NumCombined;
7731 return 0;
7732 }
7733 }
7734 }
7735 }
7736
Chris Lattner31f486c2005-01-31 05:36:43 +00007737 return 0;
7738}
7739
7740
Chris Lattner9eef8a72003-06-04 04:46:00 +00007741Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7742 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007743 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007744 BasicBlock *TrueDest;
7745 BasicBlock *FalseDest;
7746 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7747 !isa<Constant>(X)) {
7748 // Swap Destinations and condition...
7749 BI.setCondition(X);
7750 BI.setSuccessor(0, FalseDest);
7751 BI.setSuccessor(1, TrueDest);
7752 return &BI;
7753 }
7754
7755 // Cannonicalize setne -> seteq
7756 Instruction::BinaryOps Op; Value *Y;
7757 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7758 TrueDest, FalseDest)))
7759 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7760 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7761 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7762 std::string Name = I->getName(); I->setName("");
7763 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7764 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007765 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007766 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007767 BI.setSuccessor(0, FalseDest);
7768 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007769 removeFromWorkList(I);
7770 I->getParent()->getInstList().erase(I);
7771 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007772 return &BI;
7773 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007774
Chris Lattner9eef8a72003-06-04 04:46:00 +00007775 return 0;
7776}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007777
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007778Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7779 Value *Cond = SI.getCondition();
7780 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7781 if (I->getOpcode() == Instruction::Add)
7782 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7783 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7784 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007785 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007786 AddRHS));
7787 SI.setOperand(0, I->getOperand(0));
7788 WorkList.push_back(I);
7789 return &SI;
7790 }
7791 }
7792 return 0;
7793}
7794
Chris Lattner6bc98652006-03-05 00:22:33 +00007795/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7796/// is to leave as a vector operation.
7797static bool CheapToScalarize(Value *V, bool isConstant) {
7798 if (isa<ConstantAggregateZero>(V))
7799 return true;
7800 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7801 if (isConstant) return true;
7802 // If all elts are the same, we can extract.
7803 Constant *Op0 = C->getOperand(0);
7804 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7805 if (C->getOperand(i) != Op0)
7806 return false;
7807 return true;
7808 }
7809 Instruction *I = dyn_cast<Instruction>(V);
7810 if (!I) return false;
7811
7812 // Insert element gets simplified to the inserted element or is deleted if
7813 // this is constant idx extract element and its a constant idx insertelt.
7814 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7815 isa<ConstantInt>(I->getOperand(2)))
7816 return true;
7817 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7818 return true;
7819 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7820 if (BO->hasOneUse() &&
7821 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7822 CheapToScalarize(BO->getOperand(1), isConstant)))
7823 return true;
7824
7825 return false;
7826}
7827
Chris Lattner12249be2006-05-25 23:48:38 +00007828/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7829/// elements into values that are larger than the #elts in the input.
7830static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7831 unsigned NElts = SVI->getType()->getNumElements();
7832 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7833 return std::vector<unsigned>(NElts, 0);
7834 if (isa<UndefValue>(SVI->getOperand(2)))
7835 return std::vector<unsigned>(NElts, 2*NElts);
7836
7837 std::vector<unsigned> Result;
7838 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7839 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7840 if (isa<UndefValue>(CP->getOperand(i)))
7841 Result.push_back(NElts*2); // undef -> 8
7842 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007843 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00007844 return Result;
7845}
7846
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007847/// FindScalarElement - Given a vector and an element number, see if the scalar
7848/// value is already around as a register, for example if it were inserted then
7849/// extracted from the vector.
7850static Value *FindScalarElement(Value *V, unsigned EltNo) {
7851 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7852 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007853 unsigned Width = PTy->getNumElements();
7854 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007855 return UndefValue::get(PTy->getElementType());
7856
7857 if (isa<UndefValue>(V))
7858 return UndefValue::get(PTy->getElementType());
7859 else if (isa<ConstantAggregateZero>(V))
7860 return Constant::getNullValue(PTy->getElementType());
7861 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7862 return CP->getOperand(EltNo);
7863 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7864 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007865 if (!isa<ConstantInt>(III->getOperand(2)))
7866 return 0;
7867 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007868
7869 // If this is an insert to the element we are looking for, return the
7870 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007871 if (EltNo == IIElt)
7872 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007873
7874 // Otherwise, the insertelement doesn't modify the value, recurse on its
7875 // vector input.
7876 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007877 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007878 unsigned InEl = getShuffleMask(SVI)[EltNo];
7879 if (InEl < Width)
7880 return FindScalarElement(SVI->getOperand(0), InEl);
7881 else if (InEl < Width*2)
7882 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7883 else
7884 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007885 }
7886
7887 // Otherwise, we don't know.
7888 return 0;
7889}
7890
Robert Bocchinoa8352962006-01-13 22:48:06 +00007891Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007892
Chris Lattner92346c32006-03-31 18:25:14 +00007893 // If packed val is undef, replace extract with scalar undef.
7894 if (isa<UndefValue>(EI.getOperand(0)))
7895 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7896
7897 // If packed val is constant 0, replace extract with scalar 0.
7898 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7899 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7900
Robert Bocchinoa8352962006-01-13 22:48:06 +00007901 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7902 // If packed val is constant with uniform operands, replace EI
7903 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007904 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007905 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007906 if (C->getOperand(i) != op0) {
7907 op0 = 0;
7908 break;
7909 }
7910 if (op0)
7911 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007912 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007913
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007914 // If extracting a specified index from the vector, see if we can recursively
7915 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007916 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00007917 // This instruction only demands the single element from the input vector.
7918 // If the input vector has a single use, simplify it based on this use
7919 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007920 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00007921 if (EI.getOperand(0)->hasOneUse()) {
7922 uint64_t UndefElts;
7923 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00007924 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00007925 UndefElts)) {
7926 EI.setOperand(0, V);
7927 return &EI;
7928 }
7929 }
7930
Reid Spencere0fc4df2006-10-20 07:07:24 +00007931 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007932 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007933 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007934
Chris Lattner83f65782006-05-25 22:53:38 +00007935 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007936 if (I->hasOneUse()) {
7937 // Push extractelement into predecessor operation if legal and
7938 // profitable to do so
7939 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007940 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7941 if (CheapToScalarize(BO, isConstantElt)) {
7942 ExtractElementInst *newEI0 =
7943 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7944 EI.getName()+".lhs");
7945 ExtractElementInst *newEI1 =
7946 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7947 EI.getName()+".rhs");
7948 InsertNewInstBefore(newEI0, EI);
7949 InsertNewInstBefore(newEI1, EI);
7950 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7951 }
7952 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007953 Value *Ptr = InsertCastBefore(I->getOperand(0),
7954 PointerType::get(EI.getType()), EI);
7955 GetElementPtrInst *GEP =
7956 new GetElementPtrInst(Ptr, EI.getOperand(1),
7957 I->getName() + ".gep");
7958 InsertNewInstBefore(GEP, EI);
7959 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007960 }
7961 }
7962 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7963 // Extracting the inserted element?
7964 if (IE->getOperand(2) == EI.getOperand(1))
7965 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7966 // If the inserted and extracted elements are constants, they must not
7967 // be the same value, extract from the pre-inserted value instead.
7968 if (isa<Constant>(IE->getOperand(2)) &&
7969 isa<Constant>(EI.getOperand(1))) {
7970 AddUsesToWorkList(EI);
7971 EI.setOperand(0, IE->getOperand(0));
7972 return &EI;
7973 }
7974 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7975 // If this is extracting an element from a shufflevector, figure out where
7976 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007977 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7978 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00007979 Value *Src;
7980 if (SrcIdx < SVI->getType()->getNumElements())
7981 Src = SVI->getOperand(0);
7982 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7983 SrcIdx -= SVI->getType()->getNumElements();
7984 Src = SVI->getOperand(1);
7985 } else {
7986 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007987 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00007988 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007989 }
7990 }
Chris Lattner83f65782006-05-25 22:53:38 +00007991 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007992 return 0;
7993}
7994
Chris Lattner90951862006-04-16 00:51:47 +00007995/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7996/// elements from either LHS or RHS, return the shuffle mask and true.
7997/// Otherwise, return false.
7998static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7999 std::vector<Constant*> &Mask) {
8000 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8001 "Invalid CollectSingleShuffleElements");
8002 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8003
8004 if (isa<UndefValue>(V)) {
8005 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8006 return true;
8007 } else if (V == LHS) {
8008 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008009 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008010 return true;
8011 } else if (V == RHS) {
8012 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008013 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008014 return true;
8015 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8016 // If this is an insert of an extract from some other vector, include it.
8017 Value *VecOp = IEI->getOperand(0);
8018 Value *ScalarOp = IEI->getOperand(1);
8019 Value *IdxOp = IEI->getOperand(2);
8020
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008021 if (!isa<ConstantInt>(IdxOp))
8022 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008023 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008024
8025 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8026 // Okay, we can handle this if the vector we are insertinting into is
8027 // transitively ok.
8028 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8029 // If so, update the mask to reflect the inserted undef.
8030 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8031 return true;
8032 }
8033 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8034 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008035 EI->getOperand(0)->getType() == V->getType()) {
8036 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008037 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008038
8039 // This must be extracting from either LHS or RHS.
8040 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8041 // Okay, we can handle this if the vector we are insertinting into is
8042 // transitively ok.
8043 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8044 // If so, update the mask to reflect the inserted value.
8045 if (EI->getOperand(0) == LHS) {
8046 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008047 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008048 } else {
8049 assert(EI->getOperand(0) == RHS);
8050 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008051 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008052
8053 }
8054 return true;
8055 }
8056 }
8057 }
8058 }
8059 }
8060 // TODO: Handle shufflevector here!
8061
8062 return false;
8063}
8064
8065/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8066/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8067/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008068static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008069 Value *&RHS) {
8070 assert(isa<PackedType>(V->getType()) &&
8071 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008072 "Invalid shuffle!");
8073 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8074
8075 if (isa<UndefValue>(V)) {
8076 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8077 return V;
8078 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008079 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008080 return V;
8081 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8082 // If this is an insert of an extract from some other vector, include it.
8083 Value *VecOp = IEI->getOperand(0);
8084 Value *ScalarOp = IEI->getOperand(1);
8085 Value *IdxOp = IEI->getOperand(2);
8086
8087 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8088 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8089 EI->getOperand(0)->getType() == V->getType()) {
8090 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008091 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8092 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008093
8094 // Either the extracted from or inserted into vector must be RHSVec,
8095 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008096 if (EI->getOperand(0) == RHS || RHS == 0) {
8097 RHS = EI->getOperand(0);
8098 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008099 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008100 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008101 return V;
8102 }
8103
Chris Lattner90951862006-04-16 00:51:47 +00008104 if (VecOp == RHS) {
8105 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008106 // Everything but the extracted element is replaced with the RHS.
8107 for (unsigned i = 0; i != NumElts; ++i) {
8108 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008109 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008110 }
8111 return V;
8112 }
Chris Lattner90951862006-04-16 00:51:47 +00008113
8114 // If this insertelement is a chain that comes from exactly these two
8115 // vectors, return the vector and the effective shuffle.
8116 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8117 return EI->getOperand(0);
8118
Chris Lattner39fac442006-04-15 01:39:45 +00008119 }
8120 }
8121 }
Chris Lattner90951862006-04-16 00:51:47 +00008122 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008123
8124 // Otherwise, can't do anything fancy. Return an identity vector.
8125 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008126 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008127 return V;
8128}
8129
8130Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8131 Value *VecOp = IE.getOperand(0);
8132 Value *ScalarOp = IE.getOperand(1);
8133 Value *IdxOp = IE.getOperand(2);
8134
8135 // If the inserted element was extracted from some other vector, and if the
8136 // indexes are constant, try to turn this into a shufflevector operation.
8137 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8138 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8139 EI->getOperand(0)->getType() == IE.getType()) {
8140 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008141 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8142 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008143
8144 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8145 return ReplaceInstUsesWith(IE, VecOp);
8146
8147 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8148 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8149
8150 // If we are extracting a value from a vector, then inserting it right
8151 // back into the same place, just use the input vector.
8152 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8153 return ReplaceInstUsesWith(IE, VecOp);
8154
8155 // We could theoretically do this for ANY input. However, doing so could
8156 // turn chains of insertelement instructions into a chain of shufflevector
8157 // instructions, and right now we do not merge shufflevectors. As such,
8158 // only do this in a situation where it is clear that there is benefit.
8159 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8160 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8161 // the values of VecOp, except then one read from EIOp0.
8162 // Build a new shuffle mask.
8163 std::vector<Constant*> Mask;
8164 if (isa<UndefValue>(VecOp))
8165 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8166 else {
8167 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008168 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008169 NumVectorElts));
8170 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008171 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008172 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8173 ConstantPacked::get(Mask));
8174 }
8175
8176 // If this insertelement isn't used by some other insertelement, turn it
8177 // (and any insertelements it points to), into one big shuffle.
8178 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8179 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008180 Value *RHS = 0;
8181 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8182 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8183 // We now have a shuffle of LHS, RHS, Mask.
8184 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008185 }
8186 }
8187 }
8188
8189 return 0;
8190}
8191
8192
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008193Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8194 Value *LHS = SVI.getOperand(0);
8195 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008196 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008197
8198 bool MadeChange = false;
8199
Chris Lattner2deeaea2006-10-05 06:55:50 +00008200 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008201 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008202 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8203
Chris Lattner39fac442006-04-15 01:39:45 +00008204 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8205 // the undef, change them to undefs.
8206
Chris Lattner12249be2006-05-25 23:48:38 +00008207 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8208 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8209 if (LHS == RHS || isa<UndefValue>(LHS)) {
8210 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008211 // shuffle(undef,undef,mask) -> undef.
8212 return ReplaceInstUsesWith(SVI, LHS);
8213 }
8214
Chris Lattner12249be2006-05-25 23:48:38 +00008215 // Remap any references to RHS to use LHS.
8216 std::vector<Constant*> Elts;
8217 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008218 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008219 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008220 else {
8221 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8222 (Mask[i] < e && isa<UndefValue>(LHS)))
8223 Mask[i] = 2*e; // Turn into undef.
8224 else
8225 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008226 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008227 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008228 }
Chris Lattner12249be2006-05-25 23:48:38 +00008229 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008230 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008231 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008232 LHS = SVI.getOperand(0);
8233 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008234 MadeChange = true;
8235 }
8236
Chris Lattner0e477162006-05-26 00:29:06 +00008237 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008238 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008239
Chris Lattner12249be2006-05-25 23:48:38 +00008240 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8241 if (Mask[i] >= e*2) continue; // Ignore undef values.
8242 // Is this an identity shuffle of the LHS value?
8243 isLHSID &= (Mask[i] == i);
8244
8245 // Is this an identity shuffle of the RHS value?
8246 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008247 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008248
Chris Lattner12249be2006-05-25 23:48:38 +00008249 // Eliminate identity shuffles.
8250 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8251 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008252
Chris Lattner0e477162006-05-26 00:29:06 +00008253 // If the LHS is a shufflevector itself, see if we can combine it with this
8254 // one without producing an unusual shuffle. Here we are really conservative:
8255 // we are absolutely afraid of producing a shuffle mask not in the input
8256 // program, because the code gen may not be smart enough to turn a merged
8257 // shuffle into two specific shuffles: it may produce worse code. As such,
8258 // we only merge two shuffles if the result is one of the two input shuffle
8259 // masks. In this case, merging the shuffles just removes one instruction,
8260 // which we know is safe. This is good for things like turning:
8261 // (splat(splat)) -> splat.
8262 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8263 if (isa<UndefValue>(RHS)) {
8264 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8265
8266 std::vector<unsigned> NewMask;
8267 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8268 if (Mask[i] >= 2*e)
8269 NewMask.push_back(2*e);
8270 else
8271 NewMask.push_back(LHSMask[Mask[i]]);
8272
8273 // If the result mask is equal to the src shuffle or this shuffle mask, do
8274 // the replacement.
8275 if (NewMask == LHSMask || NewMask == Mask) {
8276 std::vector<Constant*> Elts;
8277 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8278 if (NewMask[i] >= e*2) {
8279 Elts.push_back(UndefValue::get(Type::UIntTy));
8280 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008281 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008282 }
8283 }
8284 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8285 LHSSVI->getOperand(1),
8286 ConstantPacked::get(Elts));
8287 }
8288 }
8289 }
8290
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008291 return MadeChange ? &SVI : 0;
8292}
8293
8294
Robert Bocchinoa8352962006-01-13 22:48:06 +00008295
Chris Lattner99f48c62002-09-02 04:59:56 +00008296void InstCombiner::removeFromWorkList(Instruction *I) {
8297 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8298 WorkList.end());
8299}
8300
Chris Lattner39c98bb2004-12-08 23:43:58 +00008301
8302/// TryToSinkInstruction - Try to move the specified instruction from its
8303/// current block into the beginning of DestBlock, which can only happen if it's
8304/// safe to move the instruction past all of the instructions between it and the
8305/// end of its block.
8306static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8307 assert(I->hasOneUse() && "Invariants didn't hold!");
8308
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008309 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8310 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008311
Chris Lattner39c98bb2004-12-08 23:43:58 +00008312 // Do not sink alloca instructions out of the entry block.
8313 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8314 return false;
8315
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008316 // We can only sink load instructions if there is nothing between the load and
8317 // the end of block that could change the value.
8318 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008319 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8320 Scan != E; ++Scan)
8321 if (Scan->mayWriteToMemory())
8322 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008323 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008324
8325 BasicBlock::iterator InsertPos = DestBlock->begin();
8326 while (isa<PHINode>(InsertPos)) ++InsertPos;
8327
Chris Lattner9f269e42005-08-08 19:11:57 +00008328 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008329 ++NumSunkInst;
8330 return true;
8331}
8332
Chris Lattner1443bc52006-05-11 17:11:52 +00008333/// OptimizeConstantExpr - Given a constant expression and target data layout
8334/// information, symbolically evaluation the constant expr to something simpler
8335/// if possible.
8336static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8337 if (!TD) return CE;
8338
8339 Constant *Ptr = CE->getOperand(0);
8340 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8341 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8342 // If this is a constant expr gep that is effectively computing an
8343 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8344 bool isFoldableGEP = true;
8345 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8346 if (!isa<ConstantInt>(CE->getOperand(i)))
8347 isFoldableGEP = false;
8348 if (isFoldableGEP) {
8349 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8350 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008351 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008352 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8353 return ConstantExpr::getCast(C, CE->getType());
8354 }
8355 }
8356
8357 return CE;
8358}
8359
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008360
8361/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8362/// all reachable code to the worklist.
8363///
8364/// This has a couple of tricks to make the code faster and more powerful. In
8365/// particular, we constant fold and DCE instructions as we go, to avoid adding
8366/// them to the worklist (this significantly speeds up instcombine on code where
8367/// many instructions are dead or constant). Additionally, if we find a branch
8368/// whose condition is a known constant, we only visit the reachable successors.
8369///
8370static void AddReachableCodeToWorklist(BasicBlock *BB,
8371 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008372 std::vector<Instruction*> &WorkList,
8373 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008374 // We have now visited this block! If we've already been here, bail out.
8375 if (!Visited.insert(BB).second) return;
8376
8377 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8378 Instruction *Inst = BBI++;
8379
8380 // DCE instruction if trivially dead.
8381 if (isInstructionTriviallyDead(Inst)) {
8382 ++NumDeadInst;
8383 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8384 Inst->eraseFromParent();
8385 continue;
8386 }
8387
8388 // ConstantProp instruction if trivially constant.
8389 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8391 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008392 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8393 Inst->replaceAllUsesWith(C);
8394 ++NumConstProp;
8395 Inst->eraseFromParent();
8396 continue;
8397 }
8398
8399 WorkList.push_back(Inst);
8400 }
8401
8402 // Recursively visit successors. If this is a branch or switch on a constant,
8403 // only visit the reachable successor.
8404 TerminatorInst *TI = BB->getTerminator();
8405 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8406 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8407 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008408 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8409 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008410 return;
8411 }
8412 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8413 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8414 // See if this is an explicit destination.
8415 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8416 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008417 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008418 return;
8419 }
8420
8421 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008422 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008423 return;
8424 }
8425 }
8426
8427 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008428 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008429}
8430
Chris Lattner113f4f42002-06-25 16:13:24 +00008431bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008432 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008433 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008434
Chris Lattner4ed40f72005-07-07 20:40:38 +00008435 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008436 // Do a depth-first traversal of the function, populate the worklist with
8437 // the reachable instructions. Ignore blocks that are not reachable. Keep
8438 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008439 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008440 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008441
Chris Lattner4ed40f72005-07-07 20:40:38 +00008442 // Do a quick scan over the function. If we find any blocks that are
8443 // unreachable, remove any instructions inside of them. This prevents
8444 // the instcombine code from having to deal with some bad special cases.
8445 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8446 if (!Visited.count(BB)) {
8447 Instruction *Term = BB->getTerminator();
8448 while (Term != BB->begin()) { // Remove instrs bottom-up
8449 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008450
Chris Lattner4ed40f72005-07-07 20:40:38 +00008451 DEBUG(std::cerr << "IC: DCE: " << *I);
8452 ++NumDeadInst;
8453
8454 if (!I->use_empty())
8455 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8456 I->eraseFromParent();
8457 }
8458 }
8459 }
Chris Lattnerca081252001-12-14 16:52:21 +00008460
8461 while (!WorkList.empty()) {
8462 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8463 WorkList.pop_back();
8464
Chris Lattner1443bc52006-05-11 17:11:52 +00008465 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008466 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008467 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008468 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008469 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008470 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008471
Chris Lattnercd517ff2005-01-28 19:32:01 +00008472 DEBUG(std::cerr << "IC: DCE: " << *I);
8473
8474 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008475 removeFromWorkList(I);
8476 continue;
8477 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008478
Chris Lattner1443bc52006-05-11 17:11:52 +00008479 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008480 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008481 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8482 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008483 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8484
Chris Lattner1443bc52006-05-11 17:11:52 +00008485 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008486 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008487 ReplaceInstUsesWith(*I, C);
8488
Chris Lattner99f48c62002-09-02 04:59:56 +00008489 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008490 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008491 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008492 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008493 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008494
Chris Lattner39c98bb2004-12-08 23:43:58 +00008495 // See if we can trivially sink this instruction to a successor basic block.
8496 if (I->hasOneUse()) {
8497 BasicBlock *BB = I->getParent();
8498 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8499 if (UserParent != BB) {
8500 bool UserIsSuccessor = false;
8501 // See if the user is one of our successors.
8502 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8503 if (*SI == UserParent) {
8504 UserIsSuccessor = true;
8505 break;
8506 }
8507
8508 // If the user is one of our immediate successors, and if that successor
8509 // only has us as a predecessors (we'd have to split the critical edge
8510 // otherwise), we can keep going.
8511 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8512 next(pred_begin(UserParent)) == pred_end(UserParent))
8513 // Okay, the CFG is simple enough, try to sink this instruction.
8514 Changed |= TryToSinkInstruction(I, UserParent);
8515 }
8516 }
8517
Chris Lattnerca081252001-12-14 16:52:21 +00008518 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008519 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008520 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008521 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008522 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008523 DEBUG(std::cerr << "IC: Old = " << *I
8524 << " New = " << *Result);
8525
Chris Lattner396dbfe2004-06-09 05:08:07 +00008526 // Everything uses the new instruction now.
8527 I->replaceAllUsesWith(Result);
8528
8529 // Push the new instruction and any users onto the worklist.
8530 WorkList.push_back(Result);
8531 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008532
8533 // Move the name to the new instruction first...
8534 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008535 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008536
8537 // Insert the new instruction into the basic block...
8538 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008539 BasicBlock::iterator InsertPos = I;
8540
8541 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8542 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8543 ++InsertPos;
8544
8545 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008546
Chris Lattner63d75af2004-05-01 23:27:23 +00008547 // Make sure that we reprocess all operands now that we reduced their
8548 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008549 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8550 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8551 WorkList.push_back(OpI);
8552
Chris Lattner396dbfe2004-06-09 05:08:07 +00008553 // Instructions can end up on the worklist more than once. Make sure
8554 // we do not process an instruction that has been deleted.
8555 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008556
8557 // Erase the old instruction.
8558 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008559 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008560 DEBUG(std::cerr << "IC: MOD = " << *I);
8561
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008562 // If the instruction was modified, it's possible that it is now dead.
8563 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008564 if (isInstructionTriviallyDead(I)) {
8565 // Make sure we process all operands now that we are reducing their
8566 // use counts.
8567 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8568 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8569 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008570
Chris Lattner63d75af2004-05-01 23:27:23 +00008571 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008572 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008573 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008574 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008575 } else {
8576 WorkList.push_back(Result);
8577 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008578 }
Chris Lattner053c0932002-05-14 15:24:07 +00008579 }
Chris Lattner260ab202002-04-18 17:39:14 +00008580 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008581 }
8582 }
8583
Chris Lattner260ab202002-04-18 17:39:14 +00008584 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008585}
8586
Brian Gaeke38b79e82004-07-27 17:43:21 +00008587FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008588 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008589}
Brian Gaeke960707c2003-11-11 22:41:34 +00008590