blob: f636442bb7fecee68419ee740c617c046f29236d [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000091
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
95 ///
96 /// Return the specified operand before it is turned into an undef.
97 ///
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
100
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
106 }
107
108 return R;
109 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000110
Chris Lattner99f48c62002-09-02 04:59:56 +0000111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000113 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000114 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000115
Chris Lattnerf12cc842002-04-28 21:27:06 +0000116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000117 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000118 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000120 }
121
Chris Lattner69193f92004-04-05 01:30:19 +0000122 TargetData &getTargetData() const { return *TD; }
123
Chris Lattner260ab202002-04-18 17:39:14 +0000124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
126 // Return Value:
127 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000128 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000129 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000130 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000134 Instruction *visitURem(BinaryOperator &I);
135 Instruction *visitSRem(BinaryOperator &I);
136 Instruction *visitFRem(BinaryOperator &I);
137 Instruction *commonRemTransforms(BinaryOperator &I);
138 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000139 Instruction *commonDivTransforms(BinaryOperator &I);
140 Instruction *commonIDivTransforms(BinaryOperator &I);
141 Instruction *visitUDiv(BinaryOperator &I);
142 Instruction *visitSDiv(BinaryOperator &I);
143 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 Instruction *visitAnd(BinaryOperator &I);
145 Instruction *visitOr (BinaryOperator &I);
146 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000147 Instruction *visitSetCondInst(SetCondInst &I);
148 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149
Chris Lattner0798af32005-01-13 20:14:25 +0000150 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
151 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000155 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000156 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
157 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000158 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000159 Instruction *visitCallInst(CallInst &CI);
160 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000161 Instruction *visitPHINode(PHINode &PN);
162 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000163 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000164 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000165 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000166 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000167 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000168 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000169 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000170 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000171 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000172
173 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000175
Chris Lattner970c33a2003-06-19 17:00:31 +0000176 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000177 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000178 bool transformConstExprCastCall(CallSite CS);
179
Chris Lattner69193f92004-04-05 01:30:19 +0000180 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000181 // InsertNewInstBefore - insert an instruction New before instruction Old
182 // in the program. Add the new instruction to the worklist.
183 //
Chris Lattner623826c2004-09-28 21:48:02 +0000184 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000185 assert(New && New->getParent() == 0 &&
186 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 BasicBlock *BB = Old.getParent();
188 BB->getInstList().insert(&Old, New); // Insert inst
189 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000190 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000191 }
192
Chris Lattner7e794272004-09-24 15:21:34 +0000193 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
194 /// This also adds the cast to the worklist. Finally, this returns the
195 /// cast.
196 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
197 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000198
Chris Lattnere79d2492006-04-06 19:19:17 +0000199 if (Constant *CV = dyn_cast<Constant>(V))
200 return ConstantExpr::getCast(CV, Ty);
201
Chris Lattner7e794272004-09-24 15:21:34 +0000202 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
203 WorkList.push_back(C);
204 return C;
205 }
206
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000207 // ReplaceInstUsesWith - This method is to be used when an instruction is
208 // found to be dead, replacable with another preexisting expression. Here
209 // we add all uses of I to the worklist, replace all uses of I with the new
210 // value, then return I, so that the inst combiner will know that I was
211 // modified.
212 //
213 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000214 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000215 if (&I != V) {
216 I.replaceAllUsesWith(V);
217 return &I;
218 } else {
219 // If we are replacing the instruction with itself, this must be in a
220 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000221 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000222 return &I;
223 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000225
Chris Lattner2590e512006-02-07 06:56:34 +0000226 // UpdateValueUsesWith - This method is to be used when an value is
227 // found to be replacable with another preexisting expression or was
228 // updated. Here we add all uses of I to the worklist, replace all uses of
229 // I with the new value (unless the instruction was just updated), then
230 // return true, so that the inst combiner will know that I was modified.
231 //
232 bool UpdateValueUsesWith(Value *Old, Value *New) {
233 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
234 if (Old != New)
235 Old->replaceAllUsesWith(New);
236 if (Instruction *I = dyn_cast<Instruction>(Old))
237 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000238 if (Instruction *I = dyn_cast<Instruction>(New))
239 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000240 return true;
241 }
242
Chris Lattner51ea1272004-02-28 05:22:00 +0000243 // EraseInstFromFunction - When dealing with an instruction that has side
244 // effects or produces a void value, we can't rely on DCE to delete the
245 // instruction. Instead, visit methods should return the value returned by
246 // this function.
247 Instruction *EraseInstFromFunction(Instruction &I) {
248 assert(I.use_empty() && "Cannot erase instruction that is used!");
249 AddUsesToWorkList(I);
250 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000251 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000252 return 0; // Don't do anything with FI
253 }
254
Chris Lattner3ac7c262003-08-13 20:16:26 +0000255 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000256 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
257 /// InsertBefore instruction. This is specialized a bit to avoid inserting
258 /// casts that are known to not do anything...
259 ///
260 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
261 Instruction *InsertBefore);
262
Chris Lattner7fb29e12003-03-11 00:12:48 +0000263 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000264 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000266
Chris Lattner0157e7f2006-02-11 09:31:47 +0000267 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
268 uint64_t &KnownZero, uint64_t &KnownOne,
269 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000270
Chris Lattner2deeaea2006-10-05 06:55:50 +0000271 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
272 uint64_t &UndefElts, unsigned Depth = 0);
273
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000274 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
275 // PHI node as operand #0, see if we can fold the instruction into the PHI
276 // (which is only possible if all operands to the PHI are constants).
277 Instruction *FoldOpIntoPhi(Instruction &I);
278
Chris Lattner7515cab2004-11-14 19:13:23 +0000279 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
280 // operator and they all are only used by the PHI, PHI together their
281 // inputs, and do the operation once, to the result of the PHI.
282 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000283 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
284
285
Chris Lattnerba1cb382003-09-19 17:17:26 +0000286 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
287 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000288
289 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
290 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000291 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
292 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000293 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000294 Instruction *MatchBSwap(BinaryOperator &I);
295
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000296 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000297 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000298
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000299 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000300}
301
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000303// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000304static unsigned getComplexity(Value *V) {
305 if (isa<Instruction>(V)) {
306 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000307 return 3;
308 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000310 if (isa<Argument>(V)) return 3;
311 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000312}
Chris Lattner260ab202002-04-18 17:39:14 +0000313
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314// isOnlyUse - Return true if this instruction will be deleted if we stop using
315// it.
316static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000317 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000318}
319
Chris Lattnere79e8542004-02-23 06:38:22 +0000320// getPromotedType - Return the specified type promoted as it would be to pass
321// though a va_arg area...
322static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000323 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000324 case Type::SByteTyID:
325 case Type::ShortTyID: return Type::IntTy;
326 case Type::UByteTyID:
327 case Type::UShortTyID: return Type::UIntTy;
328 case Type::FloatTyID: return Type::DoubleTy;
329 default: return Ty;
330 }
331}
332
Chris Lattner567b81f2005-09-13 00:40:14 +0000333/// isCast - If the specified operand is a CastInst or a constant expr cast,
334/// return the operand value, otherwise return null.
335static Value *isCast(Value *V) {
336 if (CastInst *I = dyn_cast<CastInst>(V))
337 return I->getOperand(0);
338 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
339 if (CE->getOpcode() == Instruction::Cast)
340 return CE->getOperand(0);
341 return 0;
342}
343
Chris Lattner1d441ad2006-05-06 09:00:16 +0000344enum CastType {
345 Noop = 0,
346 Truncate = 1,
347 Signext = 2,
348 Zeroext = 3
349};
350
351/// getCastType - In the future, we will split the cast instruction into these
352/// various types. Until then, we have to do the analysis here.
353static CastType getCastType(const Type *Src, const Type *Dest) {
354 assert(Src->isIntegral() && Dest->isIntegral() &&
355 "Only works on integral types!");
356 unsigned SrcSize = Src->getPrimitiveSizeInBits();
357 unsigned DestSize = Dest->getPrimitiveSizeInBits();
358
359 if (SrcSize == DestSize) return Noop;
360 if (SrcSize > DestSize) return Truncate;
361 if (Src->isSigned()) return Signext;
362 return Zeroext;
363}
364
365
366// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
367// instruction.
368//
369static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
370 const Type *DstTy, TargetData *TD) {
371
372 // It is legal to eliminate the instruction if casting A->B->A if the sizes
373 // are identical and the bits don't get reinterpreted (for example
374 // int->float->int would not be allowed).
375 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
376 return true;
377
378 // If we are casting between pointer and integer types, treat pointers as
379 // integers of the appropriate size for the code below.
380 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
381 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
382 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
383
384 // Allow free casting and conversion of sizes as long as the sign doesn't
385 // change...
386 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
387 CastType FirstCast = getCastType(SrcTy, MidTy);
388 CastType SecondCast = getCastType(MidTy, DstTy);
389
390 // Capture the effect of these two casts. If the result is a legal cast,
391 // the CastType is stored here, otherwise a special code is used.
392 static const unsigned CastResult[] = {
393 // First cast is noop
394 0, 1, 2, 3,
395 // First cast is a truncate
396 1, 1, 4, 4, // trunc->extend is not safe to eliminate
397 // First cast is a sign ext
398 2, 5, 2, 4, // signext->zeroext never ok
399 // First cast is a zero ext
400 3, 5, 3, 3,
401 };
402
403 unsigned Result = CastResult[FirstCast*4+SecondCast];
404 switch (Result) {
405 default: assert(0 && "Illegal table value!");
406 case 0:
407 case 1:
408 case 2:
409 case 3:
410 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
411 // truncates, we could eliminate more casts.
412 return (unsigned)getCastType(SrcTy, DstTy) == Result;
413 case 4:
414 return false; // Not possible to eliminate this here.
415 case 5:
416 // Sign or zero extend followed by truncate is always ok if the result
417 // is a truncate or noop.
418 CastType ResultCast = getCastType(SrcTy, DstTy);
419 if (ResultCast == Noop || ResultCast == Truncate)
420 return true;
421 // Otherwise we are still growing the value, we are only safe if the
422 // result will match the sign/zeroextendness of the result.
423 return ResultCast == FirstCast;
424 }
425 }
426
427 // If this is a cast from 'float -> double -> integer', cast from
428 // 'float -> integer' directly, as the value isn't changed by the
429 // float->double conversion.
430 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
431 DstTy->isIntegral() &&
432 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
433 return true;
434
435 // Packed type conversions don't modify bits.
436 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
437 return true;
438
439 return false;
440}
441
442/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443/// in any code being generated. It does not require codegen if V is simple
444/// enough or if the cast can be folded into other casts.
445static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
448 // If this is a noop cast, it isn't real codegen.
449 if (V->getType()->isLosslesslyConvertibleTo(Ty))
450 return false;
451
Chris Lattner99155be2006-05-25 23:24:33 +0000452 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000453 if (const CastInst *CI = dyn_cast<CastInst>(V))
454 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
455 TD))
456 return false;
457 return true;
458}
459
460/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
461/// InsertBefore instruction. This is specialized a bit to avoid inserting
462/// casts that are known to not do anything...
463///
464Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
465 Instruction *InsertBefore) {
466 if (V->getType() == DestTy) return V;
467 if (Constant *C = dyn_cast<Constant>(V))
468 return ConstantExpr::getCast(C, DestTy);
469
Reid Spencer00c482b2006-10-26 19:19:06 +0000470 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000471}
472
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000473// SimplifyCommutative - This performs a few simplifications for commutative
474// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000475//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000476// 1. Order operands such that they are listed from right (least complex) to
477// left (most complex). This puts constants before unary operators before
478// binary operators.
479//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000480// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
481// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000484 bool Changed = false;
485 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
486 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000487
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000488 if (!I.isAssociative()) return Changed;
489 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
491 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
492 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000493 Constant *Folded = ConstantExpr::get(I.getOpcode(),
494 cast<Constant>(I.getOperand(1)),
495 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496 I.setOperand(0, Op->getOperand(0));
497 I.setOperand(1, Folded);
498 return true;
499 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
500 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
501 isOnlyUse(Op) && isOnlyUse(Op1)) {
502 Constant *C1 = cast<Constant>(Op->getOperand(1));
503 Constant *C2 = cast<Constant>(Op1->getOperand(1));
504
505 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000507 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
508 Op1->getOperand(0),
509 Op1->getName(), &I);
510 WorkList.push_back(New);
511 I.setOperand(0, New);
512 I.setOperand(1, Folded);
513 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000514 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000515 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000516 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000517}
Chris Lattnerca081252001-12-14 16:52:21 +0000518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
520// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000521//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522static inline Value *dyn_castNegVal(Value *V) {
523 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000524 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525
Chris Lattner9ad0d552004-12-14 20:08:06 +0000526 // Constants can be considered to be negated values if they can be folded.
527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
528 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000529 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000530}
531
Chris Lattnerbb74e222003-03-10 23:06:50 +0000532static inline Value *dyn_castNotVal(Value *V) {
533 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000534 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000535
536 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000537 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000538 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000539 return 0;
540}
541
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542// dyn_castFoldableMul - If this value is a multiply that can be folded into
543// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000544// non-constant operand of the multiply, and set CST to point to the multiplier.
545// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000548 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000550 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000551 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000552 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000553 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000554 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000555 // The multiplier is really 1 << CST.
556 Constant *One = ConstantInt::get(V->getType(), 1);
557 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
558 return I->getOperand(0);
559 }
560 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000561 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000562}
Chris Lattner31ae8632002-08-14 17:51:49 +0000563
Chris Lattner0798af32005-01-13 20:14:25 +0000564/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565/// expression, return it.
566static User *dyn_castGetElementPtr(Value *V) {
567 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569 if (CE->getOpcode() == Instruction::GetElementPtr)
570 return cast<User>(V);
571 return false;
572}
573
Chris Lattner623826c2004-09-28 21:48:02 +0000574// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000575static ConstantInt *AddOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getAdd(C,
577 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000578}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000579static ConstantInt *SubOne(ConstantInt *C) {
580 return cast<ConstantInt>(ConstantExpr::getSub(C,
581 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000582}
583
Chris Lattner0157e7f2006-02-11 09:31:47 +0000584/// GetConstantInType - Return a ConstantInt with the specified type and value.
585///
Chris Lattneree0f2802006-02-12 02:07:56 +0000586static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000587 if (Ty->isUnsigned())
588 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000589 else if (Ty->getTypeID() == Type::BoolTyID)
590 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000591 int64_t SVal = Val;
592 SVal <<= 64-Ty->getPrimitiveSizeInBits();
593 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000594 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000595}
596
597
Chris Lattner4534dd592006-02-09 07:38:58 +0000598/// ComputeMaskedBits - Determine which of the bits specified in Mask are
599/// known to be either zero or one and return them in the KnownZero/KnownOne
600/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
601/// processing.
602static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
603 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000604 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
605 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000606 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000607 // optimized based on the contradictory assumption that it is non-zero.
608 // Because instcombine aggressively folds operations with undef args anyway,
609 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000610 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
611 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000612 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000613 KnownZero = ~KnownOne & Mask;
614 return;
615 }
616
617 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000618 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000619 return; // Limit search depth.
620
621 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000622 Instruction *I = dyn_cast<Instruction>(V);
623 if (!I) return;
624
Chris Lattnerfb296922006-05-04 17:33:35 +0000625 Mask &= V->getType()->getIntegralTypeMask();
626
Chris Lattner0157e7f2006-02-11 09:31:47 +0000627 switch (I->getOpcode()) {
628 case Instruction::And:
629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
631 Mask &= ~KnownZero;
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
640 return;
641 case Instruction::Or:
642 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
643 Mask &= ~KnownOne;
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
647
648 // Output known-0 bits are only known if clear in both the LHS & RHS.
649 KnownZero &= KnownZero2;
650 // Output known-1 are known to be set if set in either the LHS | RHS.
651 KnownOne |= KnownOne2;
652 return;
653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
664 return;
665 }
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
675 return;
676 case Instruction::Cast: {
677 const Type *SrcTy = I->getOperand(0)->getType();
678 if (!SrcTy->isIntegral()) return;
679
680 // If this is an integer truncate or noop, just look in the input.
681 if (SrcTy->getPrimitiveSizeInBits() >=
682 I->getType()->getPrimitiveSizeInBits()) {
683 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000684 return;
685 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000686
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 // Sign or Zero extension. Compute the bits in the result that are not
688 // present in the input.
689 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
690 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000691
Chris Lattner0157e7f2006-02-11 09:31:47 +0000692 // Handle zero extension.
693 if (!SrcTy->isSigned()) {
694 Mask &= SrcTy->getIntegralTypeMask();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // The top bits are known to be zero.
698 KnownZero |= NewBits;
699 } else {
700 // Sign extension.
701 Mask &= SrcTy->getIntegralTypeMask();
702 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
703 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000704
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // If the sign bit of the input is known set or clear, then we know the
706 // top bits of the result.
707 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
708 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000709 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000710 KnownOne &= ~NewBits;
711 } else if (KnownOne & InSignBit) { // Input sign bit known set
712 KnownOne |= NewBits;
713 KnownZero &= ~NewBits;
714 } else { // Input sign bit unknown
715 KnownZero &= ~NewBits;
716 KnownOne &= ~NewBits;
717 }
718 }
719 return;
720 }
721 case Instruction::Shl:
722 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000723 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
724 uint64_t ShiftAmt = SA->getZExtValue();
725 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000726 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
727 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000728 KnownZero <<= ShiftAmt;
729 KnownOne <<= ShiftAmt;
730 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000731 return;
732 }
733 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000734 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000735 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000736 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000737 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000738 uint64_t ShiftAmt = SA->getZExtValue();
739 uint64_t HighBits = (1ULL << ShiftAmt)-1;
740 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000741
Reid Spencerfdff9382006-11-08 06:47:33 +0000742 // Unsigned shift right.
743 Mask <<= ShiftAmt;
744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
746 KnownZero >>= ShiftAmt;
747 KnownOne >>= ShiftAmt;
748 KnownZero |= HighBits; // high bits known zero.
749 return;
750 }
751 break;
752 case Instruction::AShr:
753 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
754 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
755 // Compute the new bits that are at the top now.
756 uint64_t ShiftAmt = SA->getZExtValue();
757 uint64_t HighBits = (1ULL << ShiftAmt)-1;
758 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
759
760 // Signed shift right.
761 Mask <<= ShiftAmt;
762 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
763 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
764 KnownZero >>= ShiftAmt;
765 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000766
Reid Spencerfdff9382006-11-08 06:47:33 +0000767 // Handle the sign bits.
768 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
769 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000770
Reid Spencerfdff9382006-11-08 06:47:33 +0000771 if (KnownZero & SignBit) { // New bits are known zero.
772 KnownZero |= HighBits;
773 } else if (KnownOne & SignBit) { // New bits are known one.
774 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000775 }
776 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000777 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000778 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000779 }
Chris Lattner92a68652006-02-07 08:05:22 +0000780}
781
782/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
783/// this predicate to simplify operations downstream. Mask is known to be zero
784/// for bits that V cannot have.
785static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000786 uint64_t KnownZero, KnownOne;
787 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
788 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
789 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000790}
791
Chris Lattner0157e7f2006-02-11 09:31:47 +0000792/// ShrinkDemandedConstant - Check to see if the specified operand of the
793/// specified instruction is a constant integer. If so, check to see if there
794/// are any bits set in the constant that are not demanded. If so, shrink the
795/// constant and return true.
796static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
797 uint64_t Demanded) {
798 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
799 if (!OpC) return false;
800
801 // If there are no bits set that aren't demanded, nothing to do.
802 if ((~Demanded & OpC->getZExtValue()) == 0)
803 return false;
804
805 // This is producing any bits that are not needed, shrink the RHS.
806 uint64_t Val = Demanded & OpC->getZExtValue();
807 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
808 return true;
809}
810
Chris Lattneree0f2802006-02-12 02:07:56 +0000811// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
812// set of known zero and one bits, compute the maximum and minimum values that
813// could have the specified known zero and known one bits, returning them in
814// min/max.
815static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
816 uint64_t KnownZero,
817 uint64_t KnownOne,
818 int64_t &Min, int64_t &Max) {
819 uint64_t TypeBits = Ty->getIntegralTypeMask();
820 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821
822 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
823
824 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
825 // bit if it is unknown.
826 Min = KnownOne;
827 Max = KnownOne|UnknownBits;
828
829 if (SignBit & UnknownBits) { // Sign bit is unknown
830 Min |= SignBit;
831 Max &= ~SignBit;
832 }
833
834 // Sign extend the min/max values.
835 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
836 Min = (Min << ShAmt) >> ShAmt;
837 Max = (Max << ShAmt) >> ShAmt;
838}
839
840// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
841// a set of known zero and one bits, compute the maximum and minimum values that
842// could have the specified known zero and known one bits, returning them in
843// min/max.
844static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
845 uint64_t KnownZero,
846 uint64_t KnownOne,
847 uint64_t &Min,
848 uint64_t &Max) {
849 uint64_t TypeBits = Ty->getIntegralTypeMask();
850 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
851
852 // The minimum value is when the unknown bits are all zeros.
853 Min = KnownOne;
854 // The maximum value is when the unknown bits are all ones.
855 Max = KnownOne|UnknownBits;
856}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857
858
859/// SimplifyDemandedBits - Look at V. At this point, we know that only the
860/// DemandedMask bits of the result of V are ever used downstream. If we can
861/// use this information to simplify V, do so and return true. Otherwise,
862/// analyze the expression and return a mask of KnownOne and KnownZero bits for
863/// the expression (used to simplify the caller). The KnownZero/One bits may
864/// only be accurate for those bits in the DemandedMask.
865bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
866 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000867 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
869 // We know all of the bits for a constant!
870 KnownOne = CI->getZExtValue() & DemandedMask;
871 KnownZero = ~KnownOne & DemandedMask;
872 return false;
873 }
874
875 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000876 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000877 if (Depth != 0) { // Not at the root.
878 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
879 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000880 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 }
Chris Lattner2590e512006-02-07 06:56:34 +0000882 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883 // just set the DemandedMask to all bits.
884 DemandedMask = V->getType()->getIntegralTypeMask();
885 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000886 if (V != UndefValue::get(V->getType()))
887 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
888 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000889 } else if (Depth == 6) { // Limit search depth.
890 return false;
891 }
892
893 Instruction *I = dyn_cast<Instruction>(V);
894 if (!I) return false; // Only analyze instructions.
895
Chris Lattnerfb296922006-05-04 17:33:35 +0000896 DemandedMask &= V->getType()->getIntegralTypeMask();
897
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000899 switch (I->getOpcode()) {
900 default: break;
901 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 // If either the LHS or the RHS are Zero, the result is zero.
903 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
904 KnownZero, KnownOne, Depth+1))
905 return true;
906 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
907
908 // If something is known zero on the RHS, the bits aren't demanded on the
909 // LHS.
910 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
911 KnownZero2, KnownOne2, Depth+1))
912 return true;
913 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
914
915 // If all of the demanded bits are known one on one side, return the other.
916 // These bits cannot contribute to the result of the 'and'.
917 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
918 return UpdateValueUsesWith(I, I->getOperand(0));
919 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
920 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000921
922 // If all of the demanded bits in the inputs are known zeros, return zero.
923 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
924 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
925
Chris Lattner0157e7f2006-02-11 09:31:47 +0000926 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000927 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000928 return UpdateValueUsesWith(I, I);
929
930 // Output known-1 bits are only known if set in both the LHS & RHS.
931 KnownOne &= KnownOne2;
932 // Output known-0 are known to be clear if zero in either the LHS | RHS.
933 KnownZero |= KnownZero2;
934 break;
935 case Instruction::Or:
936 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
937 KnownZero, KnownOne, Depth+1))
938 return true;
939 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
940 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
941 KnownZero2, KnownOne2, Depth+1))
942 return true;
943 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
944
945 // If all of the demanded bits are known zero on one side, return the other.
946 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000947 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000948 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000949 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000950 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000951
952 // If all of the potentially set bits on one side are known to be set on
953 // the other side, just use the 'other' side.
954 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
955 (DemandedMask & (~KnownZero)))
956 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000957 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
958 (DemandedMask & (~KnownZero2)))
959 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000960
961 // If the RHS is a constant, see if we can simplify it.
962 if (ShrinkDemandedConstant(I, 1, DemandedMask))
963 return UpdateValueUsesWith(I, I);
964
965 // Output known-0 bits are only known if clear in both the LHS & RHS.
966 KnownZero &= KnownZero2;
967 // Output known-1 are known to be set if set in either the LHS | RHS.
968 KnownOne |= KnownOne2;
969 break;
970 case Instruction::Xor: {
971 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
972 KnownZero, KnownOne, Depth+1))
973 return true;
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
975 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
976 KnownZero2, KnownOne2, Depth+1))
977 return true;
978 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
979
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'xor'.
982 if ((DemandedMask & KnownZero) == DemandedMask)
983 return UpdateValueUsesWith(I, I->getOperand(0));
984 if ((DemandedMask & KnownZero2) == DemandedMask)
985 return UpdateValueUsesWith(I, I->getOperand(1));
986
987 // Output known-0 bits are known if clear or set in both the LHS & RHS.
988 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
989 // Output known-1 are known to be set if set in only one of the LHS, RHS.
990 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
991
992 // If all of the unknown bits are known to be zero on one side or the other
993 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000994 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000995 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
996 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
997 Instruction *Or =
998 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
999 I->getName());
1000 InsertNewInstBefore(Or, *I);
1001 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001002 }
1003 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004
Chris Lattner5b2edb12006-02-12 08:02:11 +00001005 // If all of the demanded bits on one side are known, and all of the set
1006 // bits on that side are also known to be set on the other side, turn this
1007 // into an AND, as we know the bits will be cleared.
1008 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1009 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1010 if ((KnownOne & KnownOne2) == KnownOne) {
1011 Constant *AndC = GetConstantInType(I->getType(),
1012 ~KnownOne & DemandedMask);
1013 Instruction *And =
1014 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1015 InsertNewInstBefore(And, *I);
1016 return UpdateValueUsesWith(I, And);
1017 }
1018 }
1019
Chris Lattner0157e7f2006-02-11 09:31:47 +00001020 // If the RHS is a constant, see if we can simplify it.
1021 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024
1025 KnownZero = KnownZeroOut;
1026 KnownOne = KnownOneOut;
1027 break;
1028 }
1029 case Instruction::Select:
1030 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1031 KnownZero, KnownOne, Depth+1))
1032 return true;
1033 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1034 KnownZero2, KnownOne2, Depth+1))
1035 return true;
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1038
1039 // If the operands are constants, see if we can simplify them.
1040 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1041 return UpdateValueUsesWith(I, I);
1042 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return UpdateValueUsesWith(I, I);
1044
1045 // Only known if known in both the LHS and RHS.
1046 KnownOne &= KnownOne2;
1047 KnownZero &= KnownZero2;
1048 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001049 case Instruction::Cast: {
1050 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001052
Chris Lattner0157e7f2006-02-11 09:31:47 +00001053 // If this is an integer truncate or noop, just look in the input.
1054 if (SrcTy->getPrimitiveSizeInBits() >=
1055 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001056 // Cast to bool is a comparison against 0, which demands all bits. We
1057 // can't propagate anything useful up.
1058 if (I->getType() == Type::BoolTy)
1059 break;
1060
Chris Lattner0157e7f2006-02-11 09:31:47 +00001061 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1062 KnownZero, KnownOne, Depth+1))
1063 return true;
1064 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1065 break;
1066 }
1067
1068 // Sign or Zero extension. Compute the bits in the result that are not
1069 // present in the input.
1070 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1071 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1072
1073 // Handle zero extension.
1074 if (!SrcTy->isSigned()) {
1075 DemandedMask &= SrcTy->getIntegralTypeMask();
1076 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1077 KnownZero, KnownOne, Depth+1))
1078 return true;
1079 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1080 // The top bits are known to be zero.
1081 KnownZero |= NewBits;
1082 } else {
1083 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001084 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1085 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1086
1087 // If any of the sign extended bits are demanded, we know that the sign
1088 // bit is demanded.
1089 if (NewBits & DemandedMask)
1090 InputDemandedBits |= InSignBit;
1091
1092 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001093 KnownZero, KnownOne, Depth+1))
1094 return true;
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1096
1097 // If the sign bit of the input is known set or clear, then we know the
1098 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001099
Chris Lattner0157e7f2006-02-11 09:31:47 +00001100 // If the input sign bit is known zero, or if the NewBits are not demanded
1101 // convert this into a zero extension.
1102 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001103 // Convert to unsigned first.
Reid Spencer00c482b2006-10-26 19:19:06 +00001104 Value *NewVal =
1105 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001106 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001108 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001109 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001110 } else if (KnownOne & InSignBit) { // Input sign bit known set
1111 KnownOne |= NewBits;
1112 KnownZero &= ~NewBits;
1113 } else { // Input sign bit unknown
1114 KnownZero &= ~NewBits;
1115 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001116 }
Chris Lattner2590e512006-02-07 06:56:34 +00001117 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001118 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001119 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001120 case Instruction::Add:
1121 // If there is a constant on the RHS, there are a variety of xformations
1122 // we can do.
1123 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1124 // If null, this should be simplified elsewhere. Some of the xforms here
1125 // won't work if the RHS is zero.
1126 if (RHS->isNullValue())
1127 break;
1128
1129 // Figure out what the input bits are. If the top bits of the and result
1130 // are not demanded, then the add doesn't demand them from its input
1131 // either.
1132
1133 // Shift the demanded mask up so that it's at the top of the uint64_t.
1134 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1135 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1136
1137 // If the top bit of the output is demanded, demand everything from the
1138 // input. Otherwise, we demand all the input bits except NLZ top bits.
1139 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1140
1141 // Find information about known zero/one bits in the input.
1142 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1143 KnownZero2, KnownOne2, Depth+1))
1144 return true;
1145
1146 // If the RHS of the add has bits set that can't affect the input, reduce
1147 // the constant.
1148 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1149 return UpdateValueUsesWith(I, I);
1150
1151 // Avoid excess work.
1152 if (KnownZero2 == 0 && KnownOne2 == 0)
1153 break;
1154
1155 // Turn it into OR if input bits are zero.
1156 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1157 Instruction *Or =
1158 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1159 I->getName());
1160 InsertNewInstBefore(Or, *I);
1161 return UpdateValueUsesWith(I, Or);
1162 }
1163
1164 // We can say something about the output known-zero and known-one bits,
1165 // depending on potential carries from the input constant and the
1166 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1167 // bits set and the RHS constant is 0x01001, then we know we have a known
1168 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1169
1170 // To compute this, we first compute the potential carry bits. These are
1171 // the bits which may be modified. I'm not aware of a better way to do
1172 // this scan.
1173 uint64_t RHSVal = RHS->getZExtValue();
1174
1175 bool CarryIn = false;
1176 uint64_t CarryBits = 0;
1177 uint64_t CurBit = 1;
1178 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1179 // Record the current carry in.
1180 if (CarryIn) CarryBits |= CurBit;
1181
1182 bool CarryOut;
1183
1184 // This bit has a carry out unless it is "zero + zero" or
1185 // "zero + anything" with no carry in.
1186 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1187 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1188 } else if (!CarryIn &&
1189 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1190 CarryOut = false; // 0 + anything has no carry out if no carry in.
1191 } else {
1192 // Otherwise, we have to assume we have a carry out.
1193 CarryOut = true;
1194 }
1195
1196 // This stage's carry out becomes the next stage's carry-in.
1197 CarryIn = CarryOut;
1198 }
1199
1200 // Now that we know which bits have carries, compute the known-1/0 sets.
1201
1202 // Bits are known one if they are known zero in one operand and one in the
1203 // other, and there is no input carry.
1204 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1205
1206 // Bits are known zero if they are known zero in both operands and there
1207 // is no input carry.
1208 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1209 }
1210 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001211 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001212 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1213 uint64_t ShiftAmt = SA->getZExtValue();
1214 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001215 KnownZero, KnownOne, Depth+1))
1216 return true;
1217 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001218 KnownZero <<= ShiftAmt;
1219 KnownOne <<= ShiftAmt;
1220 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001221 }
Chris Lattner2590e512006-02-07 06:56:34 +00001222 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001223 case Instruction::LShr:
1224 // For a logical shift right
1225 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1226 unsigned ShiftAmt = SA->getZExtValue();
1227
1228 // Compute the new bits that are at the top now.
1229 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1230 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1231 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1232 // Unsigned shift right.
1233 if (SimplifyDemandedBits(I->getOperand(0),
1234 (DemandedMask << ShiftAmt) & TypeMask,
1235 KnownZero, KnownOne, Depth+1))
1236 return true;
1237 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238 KnownZero &= TypeMask;
1239 KnownOne &= TypeMask;
1240 KnownZero >>= ShiftAmt;
1241 KnownOne >>= ShiftAmt;
1242 KnownZero |= HighBits; // high bits known zero.
1243 }
1244 break;
1245 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001246 // If this is an arithmetic shift right and only the low-bit is set, we can
1247 // always convert this into a logical shr, even if the shift amount is
1248 // variable. The low bit of the shift cannot be an input sign bit unless
1249 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001250 if (DemandedMask == 1) {
1251 // Perform the logical shift right.
1252 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1253 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001254 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001255 return UpdateValueUsesWith(I, NewVal);
1256 }
1257
Reid Spencere0fc4df2006-10-20 07:07:24 +00001258 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001260
1261 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001262 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1263 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001264 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001265 // Signed shift right.
1266 if (SimplifyDemandedBits(I->getOperand(0),
1267 (DemandedMask << ShiftAmt) & TypeMask,
1268 KnownZero, KnownOne, Depth+1))
1269 return true;
1270 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1271 KnownZero &= TypeMask;
1272 KnownOne &= TypeMask;
1273 KnownZero >>= ShiftAmt;
1274 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001275
Reid Spencerfdff9382006-11-08 06:47:33 +00001276 // Handle the sign bits.
1277 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1278 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001279
Reid Spencerfdff9382006-11-08 06:47:33 +00001280 // If the input sign bit is known to be zero, or if none of the top bits
1281 // are demanded, turn this into an unsigned shift right.
1282 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1283 // Perform the logical shift right.
1284 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1285 SA, I->getName());
1286 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1287 return UpdateValueUsesWith(I, NewVal);
1288 } else if (KnownOne & SignBit) { // New bits are known one.
1289 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001290 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001291 }
Chris Lattner2590e512006-02-07 06:56:34 +00001292 break;
1293 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001294
1295 // If the client is only demanding bits that we know, return the known
1296 // constant.
1297 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1298 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001299 return false;
1300}
1301
Chris Lattner2deeaea2006-10-05 06:55:50 +00001302
1303/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1304/// 64 or fewer elements. DemandedElts contains the set of elements that are
1305/// actually used by the caller. This method analyzes which elements of the
1306/// operand are undef and returns that information in UndefElts.
1307///
1308/// If the information about demanded elements can be used to simplify the
1309/// operation, the operation is simplified, then the resultant value is
1310/// returned. This returns null if no change was made.
1311Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1312 uint64_t &UndefElts,
1313 unsigned Depth) {
1314 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1315 assert(VWidth <= 64 && "Vector too wide to analyze!");
1316 uint64_t EltMask = ~0ULL >> (64-VWidth);
1317 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1318 "Invalid DemandedElts!");
1319
1320 if (isa<UndefValue>(V)) {
1321 // If the entire vector is undefined, just return this info.
1322 UndefElts = EltMask;
1323 return 0;
1324 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1325 UndefElts = EltMask;
1326 return UndefValue::get(V->getType());
1327 }
1328
1329 UndefElts = 0;
1330 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1331 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1332 Constant *Undef = UndefValue::get(EltTy);
1333
1334 std::vector<Constant*> Elts;
1335 for (unsigned i = 0; i != VWidth; ++i)
1336 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1337 Elts.push_back(Undef);
1338 UndefElts |= (1ULL << i);
1339 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1340 Elts.push_back(Undef);
1341 UndefElts |= (1ULL << i);
1342 } else { // Otherwise, defined.
1343 Elts.push_back(CP->getOperand(i));
1344 }
1345
1346 // If we changed the constant, return it.
1347 Constant *NewCP = ConstantPacked::get(Elts);
1348 return NewCP != CP ? NewCP : 0;
1349 } else if (isa<ConstantAggregateZero>(V)) {
1350 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1351 // set to undef.
1352 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1353 Constant *Zero = Constant::getNullValue(EltTy);
1354 Constant *Undef = UndefValue::get(EltTy);
1355 std::vector<Constant*> Elts;
1356 for (unsigned i = 0; i != VWidth; ++i)
1357 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1358 UndefElts = DemandedElts ^ EltMask;
1359 return ConstantPacked::get(Elts);
1360 }
1361
1362 if (!V->hasOneUse()) { // Other users may use these bits.
1363 if (Depth != 0) { // Not at the root.
1364 // TODO: Just compute the UndefElts information recursively.
1365 return false;
1366 }
1367 return false;
1368 } else if (Depth == 10) { // Limit search depth.
1369 return false;
1370 }
1371
1372 Instruction *I = dyn_cast<Instruction>(V);
1373 if (!I) return false; // Only analyze instructions.
1374
1375 bool MadeChange = false;
1376 uint64_t UndefElts2;
1377 Value *TmpV;
1378 switch (I->getOpcode()) {
1379 default: break;
1380
1381 case Instruction::InsertElement: {
1382 // If this is a variable index, we don't know which element it overwrites.
1383 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001384 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001385 if (Idx == 0) {
1386 // Note that we can't propagate undef elt info, because we don't know
1387 // which elt is getting updated.
1388 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1389 UndefElts2, Depth+1);
1390 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1391 break;
1392 }
1393
1394 // If this is inserting an element that isn't demanded, remove this
1395 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001396 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001397 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1398 return AddSoonDeadInstToWorklist(*I, 0);
1399
1400 // Otherwise, the element inserted overwrites whatever was there, so the
1401 // input demanded set is simpler than the output set.
1402 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1403 DemandedElts & ~(1ULL << IdxNo),
1404 UndefElts, Depth+1);
1405 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1406
1407 // The inserted element is defined.
1408 UndefElts |= 1ULL << IdxNo;
1409 break;
1410 }
1411
1412 case Instruction::And:
1413 case Instruction::Or:
1414 case Instruction::Xor:
1415 case Instruction::Add:
1416 case Instruction::Sub:
1417 case Instruction::Mul:
1418 // div/rem demand all inputs, because they don't want divide by zero.
1419 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1420 UndefElts, Depth+1);
1421 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1422 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1423 UndefElts2, Depth+1);
1424 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1425
1426 // Output elements are undefined if both are undefined. Consider things
1427 // like undef&0. The result is known zero, not undef.
1428 UndefElts &= UndefElts2;
1429 break;
1430
1431 case Instruction::Call: {
1432 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1433 if (!II) break;
1434 switch (II->getIntrinsicID()) {
1435 default: break;
1436
1437 // Binary vector operations that work column-wise. A dest element is a
1438 // function of the corresponding input elements from the two inputs.
1439 case Intrinsic::x86_sse_sub_ss:
1440 case Intrinsic::x86_sse_mul_ss:
1441 case Intrinsic::x86_sse_min_ss:
1442 case Intrinsic::x86_sse_max_ss:
1443 case Intrinsic::x86_sse2_sub_sd:
1444 case Intrinsic::x86_sse2_mul_sd:
1445 case Intrinsic::x86_sse2_min_sd:
1446 case Intrinsic::x86_sse2_max_sd:
1447 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1448 UndefElts, Depth+1);
1449 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1450 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1451 UndefElts2, Depth+1);
1452 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1453
1454 // If only the low elt is demanded and this is a scalarizable intrinsic,
1455 // scalarize it now.
1456 if (DemandedElts == 1) {
1457 switch (II->getIntrinsicID()) {
1458 default: break;
1459 case Intrinsic::x86_sse_sub_ss:
1460 case Intrinsic::x86_sse_mul_ss:
1461 case Intrinsic::x86_sse2_sub_sd:
1462 case Intrinsic::x86_sse2_mul_sd:
1463 // TODO: Lower MIN/MAX/ABS/etc
1464 Value *LHS = II->getOperand(1);
1465 Value *RHS = II->getOperand(2);
1466 // Extract the element as scalars.
1467 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1468 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1469
1470 switch (II->getIntrinsicID()) {
1471 default: assert(0 && "Case stmts out of sync!");
1472 case Intrinsic::x86_sse_sub_ss:
1473 case Intrinsic::x86_sse2_sub_sd:
1474 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1475 II->getName()), *II);
1476 break;
1477 case Intrinsic::x86_sse_mul_ss:
1478 case Intrinsic::x86_sse2_mul_sd:
1479 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1480 II->getName()), *II);
1481 break;
1482 }
1483
1484 Instruction *New =
1485 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1486 II->getName());
1487 InsertNewInstBefore(New, *II);
1488 AddSoonDeadInstToWorklist(*II, 0);
1489 return New;
1490 }
1491 }
1492
1493 // Output elements are undefined if both are undefined. Consider things
1494 // like undef&0. The result is known zero, not undef.
1495 UndefElts &= UndefElts2;
1496 break;
1497 }
1498 break;
1499 }
1500 }
1501 return MadeChange ? I : 0;
1502}
1503
Chris Lattner623826c2004-09-28 21:48:02 +00001504// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1505// true when both operands are equal...
1506//
1507static bool isTrueWhenEqual(Instruction &I) {
1508 return I.getOpcode() == Instruction::SetEQ ||
1509 I.getOpcode() == Instruction::SetGE ||
1510 I.getOpcode() == Instruction::SetLE;
1511}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001512
1513/// AssociativeOpt - Perform an optimization on an associative operator. This
1514/// function is designed to check a chain of associative operators for a
1515/// potential to apply a certain optimization. Since the optimization may be
1516/// applicable if the expression was reassociated, this checks the chain, then
1517/// reassociates the expression as necessary to expose the optimization
1518/// opportunity. This makes use of a special Functor, which must define
1519/// 'shouldApply' and 'apply' methods.
1520///
1521template<typename Functor>
1522Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1523 unsigned Opcode = Root.getOpcode();
1524 Value *LHS = Root.getOperand(0);
1525
1526 // Quick check, see if the immediate LHS matches...
1527 if (F.shouldApply(LHS))
1528 return F.apply(Root);
1529
1530 // Otherwise, if the LHS is not of the same opcode as the root, return.
1531 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001532 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001533 // Should we apply this transform to the RHS?
1534 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1535
1536 // If not to the RHS, check to see if we should apply to the LHS...
1537 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1538 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1539 ShouldApply = true;
1540 }
1541
1542 // If the functor wants to apply the optimization to the RHS of LHSI,
1543 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1544 if (ShouldApply) {
1545 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001546
Chris Lattnerb8b97502003-08-13 19:01:45 +00001547 // Now all of the instructions are in the current basic block, go ahead
1548 // and perform the reassociation.
1549 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1550
1551 // First move the selected RHS to the LHS of the root...
1552 Root.setOperand(0, LHSI->getOperand(1));
1553
1554 // Make what used to be the LHS of the root be the user of the root...
1555 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001556 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001557 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1558 return 0;
1559 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001560 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001561 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001562 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1563 BasicBlock::iterator ARI = &Root; ++ARI;
1564 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1565 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001566
1567 // Now propagate the ExtraOperand down the chain of instructions until we
1568 // get to LHSI.
1569 while (TmpLHSI != LHSI) {
1570 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001571 // Move the instruction to immediately before the chain we are
1572 // constructing to avoid breaking dominance properties.
1573 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1574 BB->getInstList().insert(ARI, NextLHSI);
1575 ARI = NextLHSI;
1576
Chris Lattnerb8b97502003-08-13 19:01:45 +00001577 Value *NextOp = NextLHSI->getOperand(1);
1578 NextLHSI->setOperand(1, ExtraOperand);
1579 TmpLHSI = NextLHSI;
1580 ExtraOperand = NextOp;
1581 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattnerb8b97502003-08-13 19:01:45 +00001583 // Now that the instructions are reassociated, have the functor perform
1584 // the transformation...
1585 return F.apply(Root);
1586 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001587
Chris Lattnerb8b97502003-08-13 19:01:45 +00001588 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1589 }
1590 return 0;
1591}
1592
1593
1594// AddRHS - Implements: X + X --> X << 1
1595struct AddRHS {
1596 Value *RHS;
1597 AddRHS(Value *rhs) : RHS(rhs) {}
1598 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1599 Instruction *apply(BinaryOperator &Add) const {
1600 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1601 ConstantInt::get(Type::UByteTy, 1));
1602 }
1603};
1604
1605// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1606// iff C1&C2 == 0
1607struct AddMaskingAnd {
1608 Constant *C2;
1609 AddMaskingAnd(Constant *c) : C2(c) {}
1610 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001611 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001612 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001613 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001614 }
1615 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001616 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001617 }
1618};
1619
Chris Lattner86102b82005-01-01 16:22:27 +00001620static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001621 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001622 if (isa<CastInst>(I)) {
1623 if (Constant *SOC = dyn_cast<Constant>(SO))
1624 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001625
Chris Lattner86102b82005-01-01 16:22:27 +00001626 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1627 SO->getName() + ".cast"), I);
1628 }
1629
Chris Lattner183b3362004-04-09 19:05:30 +00001630 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001631 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1632 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001633
Chris Lattner183b3362004-04-09 19:05:30 +00001634 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1635 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001636 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1637 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001638 }
1639
1640 Value *Op0 = SO, *Op1 = ConstOperand;
1641 if (!ConstIsRHS)
1642 std::swap(Op0, Op1);
1643 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1645 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1646 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1647 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001648 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001649 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001650 abort();
1651 }
Chris Lattner86102b82005-01-01 16:22:27 +00001652 return IC->InsertNewInstBefore(New, I);
1653}
1654
1655// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1656// constant as the other operand, try to fold the binary operator into the
1657// select arguments. This also works for Cast instructions, which obviously do
1658// not have a second operand.
1659static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1660 InstCombiner *IC) {
1661 // Don't modify shared select instructions
1662 if (!SI->hasOneUse()) return 0;
1663 Value *TV = SI->getOperand(1);
1664 Value *FV = SI->getOperand(2);
1665
1666 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001667 // Bool selects with constant operands can be folded to logical ops.
1668 if (SI->getType() == Type::BoolTy) return 0;
1669
Chris Lattner86102b82005-01-01 16:22:27 +00001670 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1671 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1672
1673 return new SelectInst(SI->getCondition(), SelectTrueVal,
1674 SelectFalseVal);
1675 }
1676 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001677}
1678
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001679
1680/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1681/// node as operand #0, see if we can fold the instruction into the PHI (which
1682/// is only possible if all operands to the PHI are constants).
1683Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1684 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001685 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001686 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001687
Chris Lattner04689872006-09-09 22:02:56 +00001688 // Check to see if all of the operands of the PHI are constants. If there is
1689 // one non-constant value, remember the BB it is. If there is more than one
1690 // bail out.
1691 BasicBlock *NonConstBB = 0;
1692 for (unsigned i = 0; i != NumPHIValues; ++i)
1693 if (!isa<Constant>(PN->getIncomingValue(i))) {
1694 if (NonConstBB) return 0; // More than one non-const value.
1695 NonConstBB = PN->getIncomingBlock(i);
1696
1697 // If the incoming non-constant value is in I's block, we have an infinite
1698 // loop.
1699 if (NonConstBB == I.getParent())
1700 return 0;
1701 }
1702
1703 // If there is exactly one non-constant value, we can insert a copy of the
1704 // operation in that block. However, if this is a critical edge, we would be
1705 // inserting the computation one some other paths (e.g. inside a loop). Only
1706 // do this if the pred block is unconditionally branching into the phi block.
1707 if (NonConstBB) {
1708 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1709 if (!BI || !BI->isUnconditional()) return 0;
1710 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001711
1712 // Okay, we can do the transformation: create the new PHI node.
1713 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1714 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001715 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001716 InsertNewInstBefore(NewPN, *PN);
1717
1718 // Next, add all of the operands to the PHI.
1719 if (I.getNumOperands() == 2) {
1720 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001721 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001722 Value *InV;
1723 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1724 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1725 } else {
1726 assert(PN->getIncomingBlock(i) == NonConstBB);
1727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1728 InV = BinaryOperator::create(BO->getOpcode(),
1729 PN->getIncomingValue(i), C, "phitmp",
1730 NonConstBB->getTerminator());
1731 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1732 InV = new ShiftInst(SI->getOpcode(),
1733 PN->getIncomingValue(i), C, "phitmp",
1734 NonConstBB->getTerminator());
1735 else
1736 assert(0 && "Unknown binop!");
1737
1738 WorkList.push_back(cast<Instruction>(InV));
1739 }
1740 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001741 }
1742 } else {
1743 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1744 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001745 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001746 Value *InV;
1747 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1748 InV = ConstantExpr::getCast(InC, RetTy);
1749 } else {
1750 assert(PN->getIncomingBlock(i) == NonConstBB);
1751 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1752 NonConstBB->getTerminator());
1753 WorkList.push_back(cast<Instruction>(InV));
1754 }
1755 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001756 }
1757 }
1758 return ReplaceInstUsesWith(I, NewPN);
1759}
1760
Chris Lattner113f4f42002-06-25 16:13:24 +00001761Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001762 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001763 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001764
Chris Lattnercf4a9962004-04-10 22:01:55 +00001765 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001766 // X + undef -> undef
1767 if (isa<UndefValue>(RHS))
1768 return ReplaceInstUsesWith(I, RHS);
1769
Chris Lattnercf4a9962004-04-10 22:01:55 +00001770 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001771 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1772 if (RHSC->isNullValue())
1773 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001774 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1775 if (CFP->isExactlyValue(-0.0))
1776 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001777 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001778
Chris Lattnercf4a9962004-04-10 22:01:55 +00001779 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001780 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001781 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001782 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001783 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001784
1785 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1786 // (X & 254)+1 -> (X&254)|1
1787 uint64_t KnownZero, KnownOne;
1788 if (!isa<PackedType>(I.getType()) &&
1789 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1790 KnownZero, KnownOne))
1791 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001792 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001793
1794 if (isa<PHINode>(LHS))
1795 if (Instruction *NV = FoldOpIntoPhi(I))
1796 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001797
Chris Lattner330628a2006-01-06 17:59:59 +00001798 ConstantInt *XorRHS = 0;
1799 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001800 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1801 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1802 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1803 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1804
1805 uint64_t C0080Val = 1ULL << 31;
1806 int64_t CFF80Val = -C0080Val;
1807 unsigned Size = 32;
1808 do {
1809 if (TySizeBits > Size) {
1810 bool Found = false;
1811 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1812 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1813 if (RHSSExt == CFF80Val) {
1814 if (XorRHS->getZExtValue() == C0080Val)
1815 Found = true;
1816 } else if (RHSZExt == C0080Val) {
1817 if (XorRHS->getSExtValue() == CFF80Val)
1818 Found = true;
1819 }
1820 if (Found) {
1821 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001822 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001823 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001824 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001825 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001826 Size = 0; // Not a sign ext, but can't be any others either.
1827 goto FoundSExt;
1828 }
1829 }
1830 Size >>= 1;
1831 C0080Val >>= Size;
1832 CFF80Val >>= Size;
1833 } while (Size >= 8);
1834
1835FoundSExt:
1836 const Type *MiddleType = 0;
1837 switch (Size) {
1838 default: break;
1839 case 32: MiddleType = Type::IntTy; break;
1840 case 16: MiddleType = Type::ShortTy; break;
1841 case 8: MiddleType = Type::SByteTy; break;
1842 }
1843 if (MiddleType) {
1844 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1845 InsertNewInstBefore(NewTrunc, I);
1846 return new CastInst(NewTrunc, I.getType());
1847 }
1848 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001849 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001850
Chris Lattnerb8b97502003-08-13 19:01:45 +00001851 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001852 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001853 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001854
1855 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1856 if (RHSI->getOpcode() == Instruction::Sub)
1857 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1858 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1859 }
1860 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1861 if (LHSI->getOpcode() == Instruction::Sub)
1862 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1863 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1864 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001865 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001866
Chris Lattner147e9752002-05-08 22:46:53 +00001867 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001868 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001869 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001870
1871 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001872 if (!isa<Constant>(RHS))
1873 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001874 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001875
Misha Brukmanb1c93172005-04-21 23:48:37 +00001876
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001877 ConstantInt *C2;
1878 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1879 if (X == RHS) // X*C + X --> X * (C+1)
1880 return BinaryOperator::createMul(RHS, AddOne(C2));
1881
1882 // X*C1 + X*C2 --> X * (C1+C2)
1883 ConstantInt *C1;
1884 if (X == dyn_castFoldableMul(RHS, C1))
1885 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001886 }
1887
1888 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001889 if (dyn_castFoldableMul(RHS, C2) == LHS)
1890 return BinaryOperator::createMul(LHS, AddOne(C2));
1891
Chris Lattner57c8d992003-02-18 19:57:07 +00001892
Chris Lattnerb8b97502003-08-13 19:01:45 +00001893 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001895 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001896
Chris Lattnerb9cde762003-10-02 15:11:26 +00001897 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001898 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001899 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1900 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1901 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001902 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001903
Chris Lattnerbff91d92004-10-08 05:07:56 +00001904 // (X & FF00) + xx00 -> (X+xx00) & FF00
1905 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1906 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1907 if (Anded == CRHS) {
1908 // See if all bits from the first bit set in the Add RHS up are included
1909 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001910 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001911
1912 // Form a mask of all bits from the lowest bit added through the top.
1913 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001914 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001915
1916 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001917 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001918
Chris Lattnerbff91d92004-10-08 05:07:56 +00001919 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1920 // Okay, the xform is safe. Insert the new add pronto.
1921 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1922 LHS->getName()), I);
1923 return BinaryOperator::createAnd(NewAdd, C2);
1924 }
1925 }
1926 }
1927
Chris Lattnerd4252a72004-07-30 07:50:03 +00001928 // Try to fold constant add into select arguments.
1929 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001930 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001931 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001932 }
1933
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001934 // add (cast *A to intptrtype) B ->
1935 // cast (GEP (cast *A to sbyte*) B) ->
1936 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001937 {
1938 CastInst* CI = dyn_cast<CastInst>(LHS);
1939 Value* Other = RHS;
1940 if (!CI) {
1941 CI = dyn_cast<CastInst>(RHS);
1942 Other = LHS;
1943 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001944 if (CI && CI->getType()->isSized() &&
1945 (CI->getType()->getPrimitiveSize() ==
1946 TD->getIntPtrType()->getPrimitiveSize())
1947 && isa<PointerType>(CI->getOperand(0)->getType())) {
1948 Value* I2 = InsertCastBefore(CI->getOperand(0),
1949 PointerType::get(Type::SByteTy), I);
1950 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1951 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001952 }
1953 }
1954
Chris Lattner113f4f42002-06-25 16:13:24 +00001955 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001956}
1957
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001958// isSignBit - Return true if the value represented by the constant only has the
1959// highest order bit set.
1960static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001961 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001963}
1964
Chris Lattner022167f2004-03-13 00:11:49 +00001965/// RemoveNoopCast - Strip off nonconverting casts from the value.
1966///
1967static Value *RemoveNoopCast(Value *V) {
1968 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1969 const Type *CTy = CI->getType();
1970 const Type *OpTy = CI->getOperand(0)->getType();
1971 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001972 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001973 return RemoveNoopCast(CI->getOperand(0));
1974 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1975 return RemoveNoopCast(CI->getOperand(0));
1976 }
1977 return V;
1978}
1979
Chris Lattner113f4f42002-06-25 16:13:24 +00001980Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001982
Chris Lattnere6794492002-08-12 21:17:25 +00001983 if (Op0 == Op1) // sub X, X -> 0
1984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001985
Chris Lattnere6794492002-08-12 21:17:25 +00001986 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001987 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001988 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001989
Chris Lattner81a7a232004-10-16 18:11:37 +00001990 if (isa<UndefValue>(Op0))
1991 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1992 if (isa<UndefValue>(Op1))
1993 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1994
Chris Lattner8f2f5982003-11-05 01:06:05 +00001995 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1996 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001997 if (C->isAllOnesValue())
1998 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001999
Chris Lattner8f2f5982003-11-05 01:06:05 +00002000 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002001 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002002 if (match(Op1, m_Not(m_Value(X))))
2003 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002004 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00002005 // -((uint)X >> 31) -> ((int)X >> 31)
2006 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002007 if (C->isNullValue()) {
2008 Value *NoopCastedRHS = RemoveNoopCast(Op1);
2009 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00002010 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002011 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002012 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002013 if (CU->getZExtValue() ==
2014 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002015 // Ok, the transformation is safe. Insert AShr.
2016 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2017 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002018 }
2019 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002020 }
2021 else if (SI->getOpcode() == Instruction::AShr) {
2022 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2023 // Check to see if we are shifting out everything but the sign bit.
2024 if (CU->getZExtValue() ==
2025 SI->getType()->getPrimitiveSizeInBits()-1) {
2026 // Ok, the transformation is safe. Insert LShr.
2027 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2028 CU, SI->getName());
2029 }
2030 }
2031 }
Chris Lattner022167f2004-03-13 00:11:49 +00002032 }
Chris Lattner183b3362004-04-09 19:05:30 +00002033
2034 // Try to fold constant sub into select arguments.
2035 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002036 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002037 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002038
2039 if (isa<PHINode>(Op0))
2040 if (Instruction *NV = FoldOpIntoPhi(I))
2041 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002042 }
2043
Chris Lattnera9be4492005-04-07 16:15:25 +00002044 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2045 if (Op1I->getOpcode() == Instruction::Add &&
2046 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002047 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002048 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002049 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002050 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002051 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2052 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2053 // C1-(X+C2) --> (C1-C2)-X
2054 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2055 Op1I->getOperand(0));
2056 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002057 }
2058
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002059 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002060 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2061 // is not used by anyone else...
2062 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002063 if (Op1I->getOpcode() == Instruction::Sub &&
2064 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002065 // Swap the two operands of the subexpr...
2066 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2067 Op1I->setOperand(0, IIOp1);
2068 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002069
Chris Lattner3082c5a2003-02-18 19:28:33 +00002070 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002071 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002072 }
2073
2074 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2075 //
2076 if (Op1I->getOpcode() == Instruction::And &&
2077 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2078 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2079
Chris Lattner396dbfe2004-06-09 05:08:07 +00002080 Value *NewNot =
2081 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002082 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002083 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002084
Reid Spencer3c514952006-10-16 23:08:08 +00002085 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002086 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002087 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002088 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002089 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002090 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002091 ConstantExpr::getNeg(DivRHS));
2092
Chris Lattner57c8d992003-02-18 19:57:07 +00002093 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002094 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002095 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002096 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002097 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002098 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002099 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002100 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002101 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002102
Chris Lattner47060462005-04-07 17:14:51 +00002103 if (!Op0->getType()->isFloatingPoint())
2104 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2105 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002106 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2107 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2108 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2109 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002110 } else if (Op0I->getOpcode() == Instruction::Sub) {
2111 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2112 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002113 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002114
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002115 ConstantInt *C1;
2116 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2117 if (X == Op1) { // X*C - X --> X * (C-1)
2118 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2119 return BinaryOperator::createMul(Op1, CP1);
2120 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002121
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002122 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2123 if (X == dyn_castFoldableMul(Op1, C2))
2124 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2125 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002126 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002127}
2128
Chris Lattnere79e8542004-02-23 06:38:22 +00002129/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2130/// really just returns true if the most significant (sign) bit is set.
2131static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2132 if (RHS->getType()->isSigned()) {
2133 // True if source is LHS < 0 or LHS <= -1
2134 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2135 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2136 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002137 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002138 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2139 // the size of the integer type.
2140 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002141 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002142 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002143 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002144 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002145 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002146 }
2147 return false;
2148}
2149
Chris Lattner113f4f42002-06-25 16:13:24 +00002150Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002151 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002152 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002153
Chris Lattner81a7a232004-10-16 18:11:37 +00002154 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2156
Chris Lattnere6794492002-08-12 21:17:25 +00002157 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002158 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2159 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002160
2161 // ((X << C1)*C2) == (X * (C2 << C1))
2162 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2163 if (SI->getOpcode() == Instruction::Shl)
2164 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002165 return BinaryOperator::createMul(SI->getOperand(0),
2166 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002167
Chris Lattnercce81be2003-09-11 22:24:54 +00002168 if (CI->isNullValue())
2169 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2170 if (CI->equalsInt(1)) // X * 1 == X
2171 return ReplaceInstUsesWith(I, Op0);
2172 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002173 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002174
Reid Spencere0fc4df2006-10-20 07:07:24 +00002175 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002176 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2177 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002178 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002179 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002180 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002181 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002182 if (Op1F->isNullValue())
2183 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002184
Chris Lattner3082c5a2003-02-18 19:28:33 +00002185 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2186 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2187 if (Op1F->getValue() == 1.0)
2188 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2189 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002190
2191 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2192 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2193 isa<ConstantInt>(Op0I->getOperand(1))) {
2194 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2195 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2196 Op1, "tmp");
2197 InsertNewInstBefore(Add, I);
2198 Value *C1C2 = ConstantExpr::getMul(Op1,
2199 cast<Constant>(Op0I->getOperand(1)));
2200 return BinaryOperator::createAdd(Add, C1C2);
2201
2202 }
Chris Lattner183b3362004-04-09 19:05:30 +00002203
2204 // Try to fold constant mul into select arguments.
2205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002206 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002207 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002208
2209 if (isa<PHINode>(Op0))
2210 if (Instruction *NV = FoldOpIntoPhi(I))
2211 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002212 }
2213
Chris Lattner934a64cf2003-03-10 23:23:04 +00002214 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2215 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002216 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002217
Chris Lattner2635b522004-02-23 05:39:21 +00002218 // If one of the operands of the multiply is a cast from a boolean value, then
2219 // we know the bool is either zero or one, so this is a 'masking' multiply.
2220 // See if we can simplify things based on how the boolean was originally
2221 // formed.
2222 CastInst *BoolCast = 0;
2223 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2224 if (CI->getOperand(0)->getType() == Type::BoolTy)
2225 BoolCast = CI;
2226 if (!BoolCast)
2227 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2228 if (CI->getOperand(0)->getType() == Type::BoolTy)
2229 BoolCast = CI;
2230 if (BoolCast) {
2231 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2232 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2233 const Type *SCOpTy = SCIOp0->getType();
2234
Chris Lattnere79e8542004-02-23 06:38:22 +00002235 // If the setcc is true iff the sign bit of X is set, then convert this
2236 // multiply into a shift/and combination.
2237 if (isa<ConstantInt>(SCIOp1) &&
2238 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002239 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002240 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002241 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002242 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002243 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002244 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002245 }
2246
2247 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002248 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002249 BoolCast->getOperand(0)->getName()+
2250 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002251
2252 // If the multiply type is not the same as the source type, sign extend
2253 // or truncate to the multiply type.
2254 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002255 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002256
Chris Lattner2635b522004-02-23 05:39:21 +00002257 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002258 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002259 }
2260 }
2261 }
2262
Chris Lattner113f4f42002-06-25 16:13:24 +00002263 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002264}
2265
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266/// This function implements the transforms on div instructions that work
2267/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2268/// used by the visitors to those instructions.
2269/// @brief Transforms common to all three div instructions
2270Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002272
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002273 // undef / X -> 0
2274 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002275 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276
2277 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002278 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002280
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002281 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002282 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2283 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002284 // same basic block, then we replace the select with Y, and the condition
2285 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002286 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002287 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002288 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2289 if (ST->isNullValue()) {
2290 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2291 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002292 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002293 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2294 I.setOperand(1, SI->getOperand(2));
2295 else
2296 UpdateValueUsesWith(SI, SI->getOperand(2));
2297 return &I;
2298 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002299
Chris Lattnerd79dc792006-09-09 20:26:32 +00002300 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2301 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2302 if (ST->isNullValue()) {
2303 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2304 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002305 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002306 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2307 I.setOperand(1, SI->getOperand(1));
2308 else
2309 UpdateValueUsesWith(SI, SI->getOperand(1));
2310 return &I;
2311 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002312 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002313
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002314 return 0;
2315}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002316
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002317/// This function implements the transforms common to both integer division
2318/// instructions (udiv and sdiv). It is called by the visitors to those integer
2319/// division instructions.
2320/// @brief Common integer divide transforms
2321Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2323
2324 if (Instruction *Common = commonDivTransforms(I))
2325 return Common;
2326
2327 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2328 // div X, 1 == X
2329 if (RHS->equalsInt(1))
2330 return ReplaceInstUsesWith(I, Op0);
2331
2332 // (X / C1) / C2 -> X / (C1*C2)
2333 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2334 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2335 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2336 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2337 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002338 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002339
2340 if (!RHS->isNullValue()) { // avoid X udiv 0
2341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2342 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2343 return R;
2344 if (isa<PHINode>(Op0))
2345 if (Instruction *NV = FoldOpIntoPhi(I))
2346 return NV;
2347 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002348 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002349
Chris Lattner3082c5a2003-02-18 19:28:33 +00002350 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002351 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002352 if (LHS->equalsInt(0))
2353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2354
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002355 return 0;
2356}
2357
2358Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2360
2361 // Handle the integer div common cases
2362 if (Instruction *Common = commonIDivTransforms(I))
2363 return Common;
2364
2365 // X udiv C^2 -> X >> C
2366 // Check to see if this is an unsigned division with an exact power of 2,
2367 // if so, convert to a right shift.
2368 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2369 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2370 if (isPowerOf2_64(Val)) {
2371 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 return new ShiftInst(Instruction::LShr, Op0,
2373 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002374 }
2375 }
2376
2377 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2378 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2379 if (RHSI->getOpcode() == Instruction::Shl &&
2380 isa<ConstantInt>(RHSI->getOperand(0))) {
2381 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2382 if (isPowerOf2_64(C1)) {
2383 Value *N = RHSI->getOperand(1);
2384 const Type* NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002385 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 Constant *C2V = ConstantInt::get(NTy, C2);
2387 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002388 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002389 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002390 }
2391 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002392 }
2393
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002394 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2395 // where C1&C2 are powers of two.
2396 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2397 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2398 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2399 if (!STO->isNullValue() && !STO->isNullValue()) {
2400 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2401 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2402 // Compute the shift amounts
2403 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002404 // Construct the "on true" case of the select
2405 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2406 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002407 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002408 TSI = InsertNewInstBefore(TSI, I);
2409
2410 // Construct the "on false" case of the select
2411 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2412 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002413 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002414 FSI = InsertNewInstBefore(FSI, I);
2415
2416 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002417 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002418 }
2419 }
2420 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002421 return 0;
2422}
2423
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002424Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2426
2427 // Handle the integer div common cases
2428 if (Instruction *Common = commonIDivTransforms(I))
2429 return Common;
2430
2431 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2432 // sdiv X, -1 == -X
2433 if (RHS->isAllOnesValue())
2434 return BinaryOperator::createNeg(Op0);
2435
2436 // -X/C -> X/-C
2437 if (Value *LHSNeg = dyn_castNegVal(Op0))
2438 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2439 }
2440
2441 // If the sign bits of both operands are zero (i.e. we can prove they are
2442 // unsigned inputs), turn this into a udiv.
2443 if (I.getType()->isInteger()) {
2444 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2445 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2446 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2447 }
2448 }
2449
2450 return 0;
2451}
2452
2453Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2454 return commonDivTransforms(I);
2455}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002456
Chris Lattner85dda9a2006-03-02 06:50:58 +00002457/// GetFactor - If we can prove that the specified value is at least a multiple
2458/// of some factor, return that factor.
2459static Constant *GetFactor(Value *V) {
2460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2461 return CI;
2462
2463 // Unless we can be tricky, we know this is a multiple of 1.
2464 Constant *Result = ConstantInt::get(V->getType(), 1);
2465
2466 Instruction *I = dyn_cast<Instruction>(V);
2467 if (!I) return Result;
2468
2469 if (I->getOpcode() == Instruction::Mul) {
2470 // Handle multiplies by a constant, etc.
2471 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2472 GetFactor(I->getOperand(1)));
2473 } else if (I->getOpcode() == Instruction::Shl) {
2474 // (X<<C) -> X * (1 << C)
2475 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2476 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2477 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2478 }
2479 } else if (I->getOpcode() == Instruction::And) {
2480 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2481 // X & 0xFFF0 is known to be a multiple of 16.
2482 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2483 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2484 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002485 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002486 }
2487 } else if (I->getOpcode() == Instruction::Cast) {
2488 Value *Op = I->getOperand(0);
2489 // Only handle int->int casts.
2490 if (!Op->getType()->isInteger()) return Result;
2491 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2492 }
2493 return Result;
2494}
2495
Reid Spencer7eb55b32006-11-02 01:53:59 +00002496/// This function implements the transforms on rem instructions that work
2497/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2498/// is used by the visitors to those instructions.
2499/// @brief Transforms common to all three rem instructions
2500Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002501 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002502
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002503 // 0 % X == 0, we don't need to preserve faults!
2504 if (Constant *LHS = dyn_cast<Constant>(Op0))
2505 if (LHS->isNullValue())
2506 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2507
2508 if (isa<UndefValue>(Op0)) // undef % X -> 0
2509 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2510 if (isa<UndefValue>(Op1))
2511 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002512
2513 // Handle cases involving: rem X, (select Cond, Y, Z)
2514 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2515 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2516 // the same basic block, then we replace the select with Y, and the
2517 // condition of the select with false (if the cond value is in the same
2518 // BB). If the select has uses other than the div, this allows them to be
2519 // simplified also.
2520 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2521 if (ST->isNullValue()) {
2522 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2523 if (CondI && CondI->getParent() == I.getParent())
2524 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2525 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2526 I.setOperand(1, SI->getOperand(2));
2527 else
2528 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002529 return &I;
2530 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002531 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2532 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2533 if (ST->isNullValue()) {
2534 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2535 if (CondI && CondI->getParent() == I.getParent())
2536 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2537 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2538 I.setOperand(1, SI->getOperand(1));
2539 else
2540 UpdateValueUsesWith(SI, SI->getOperand(1));
2541 return &I;
2542 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002543 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002544
Reid Spencer7eb55b32006-11-02 01:53:59 +00002545 return 0;
2546}
2547
2548/// This function implements the transforms common to both integer remainder
2549/// instructions (urem and srem). It is called by the visitors to those integer
2550/// remainder instructions.
2551/// @brief Common integer remainder transforms
2552Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2554
2555 if (Instruction *common = commonRemTransforms(I))
2556 return common;
2557
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002558 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002559 // X % 0 == undef, we don't need to preserve faults!
2560 if (RHS->equalsInt(0))
2561 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2562
Chris Lattner3082c5a2003-02-18 19:28:33 +00002563 if (RHS->equalsInt(1)) // X % 1 == 0
2564 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2565
Chris Lattnerb70f1412006-02-28 05:49:21 +00002566 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2568 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2569 return R;
2570 } else if (isa<PHINode>(Op0I)) {
2571 if (Instruction *NV = FoldOpIntoPhi(I))
2572 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002573 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002574 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2575 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002577 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002578 }
2579
Reid Spencer7eb55b32006-11-02 01:53:59 +00002580 return 0;
2581}
2582
2583Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2585
2586 if (Instruction *common = commonIRemTransforms(I))
2587 return common;
2588
2589 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2590 // X urem C^2 -> X and C
2591 // Check to see if this is an unsigned remainder with an exact power of 2,
2592 // if so, convert to a bitwise and.
2593 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2594 if (isPowerOf2_64(C->getZExtValue()))
2595 return BinaryOperator::createAnd(Op0, SubOne(C));
2596 }
2597
Chris Lattner2e90b732006-02-05 07:54:04 +00002598 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002599 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2600 if (RHSI->getOpcode() == Instruction::Shl &&
2601 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002602 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002603 if (isPowerOf2_64(C1)) {
2604 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2605 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2606 "tmp"), I);
2607 return BinaryOperator::createAnd(Op0, Add);
2608 }
2609 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002610 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002611
Reid Spencer7eb55b32006-11-02 01:53:59 +00002612 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2613 // where C1&C2 are powers of two.
2614 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2615 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2616 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2617 // STO == 0 and SFO == 0 handled above.
2618 if (isPowerOf2_64(STO->getZExtValue()) &&
2619 isPowerOf2_64(SFO->getZExtValue())) {
2620 Value *TrueAnd = InsertNewInstBefore(
2621 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2622 Value *FalseAnd = InsertNewInstBefore(
2623 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2624 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2625 }
2626 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002627 }
2628
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002629 return 0;
2630}
2631
Reid Spencer7eb55b32006-11-02 01:53:59 +00002632Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2633 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2634
2635 if (Instruction *common = commonIRemTransforms(I))
2636 return common;
2637
2638 if (Value *RHSNeg = dyn_castNegVal(Op1))
2639 if (!isa<ConstantInt>(RHSNeg) ||
2640 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2641 // X % -Y -> X % Y
2642 AddUsesToWorkList(I);
2643 I.setOperand(1, RHSNeg);
2644 return &I;
2645 }
2646
2647 // If the top bits of both operands are zero (i.e. we can prove they are
2648 // unsigned inputs), turn this into a urem.
2649 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2650 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2651 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2652 return BinaryOperator::createURem(Op0, Op1, I.getName());
2653 }
2654
2655 return 0;
2656}
2657
2658Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002659 return commonRemTransforms(I);
2660}
2661
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002662// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002663static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002664 if (C->getType()->isUnsigned())
2665 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002666
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002667 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002668 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002669 int64_t Val = INT64_MAX; // All ones
2670 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002671 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002672}
2673
2674// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002675static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002676 if (C->getType()->isUnsigned())
2677 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002678
2679 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002680 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002681 int64_t Val = -1; // All ones
2682 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002683 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002684}
2685
Chris Lattner35167c32004-06-09 07:59:58 +00002686// isOneBitSet - Return true if there is exactly one bit set in the specified
2687// constant.
2688static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002689 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002690 return V && (V & (V-1)) == 0;
2691}
2692
Chris Lattner8fc5af42004-09-23 21:46:38 +00002693#if 0 // Currently unused
2694// isLowOnes - Return true if the constant is of the form 0+1+.
2695static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002696 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002697
2698 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002699 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002700
2701 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2702 return U && V && (U & V) == 0;
2703}
2704#endif
2705
2706// isHighOnes - Return true if the constant is of the form 1+0+.
2707// This is the same as lowones(~X).
2708static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002709 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002710 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002711
2712 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002713 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002714
2715 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2716 return U && V && (U & V) == 0;
2717}
2718
2719
Chris Lattner3ac7c262003-08-13 20:16:26 +00002720/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2721/// are carefully arranged to allow folding of expressions such as:
2722///
2723/// (A < B) | (A > B) --> (A != B)
2724///
2725/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2726/// represents that the comparison is true if A == B, and bit value '1' is true
2727/// if A < B.
2728///
2729static unsigned getSetCondCode(const SetCondInst *SCI) {
2730 switch (SCI->getOpcode()) {
2731 // False -> 0
2732 case Instruction::SetGT: return 1;
2733 case Instruction::SetEQ: return 2;
2734 case Instruction::SetGE: return 3;
2735 case Instruction::SetLT: return 4;
2736 case Instruction::SetNE: return 5;
2737 case Instruction::SetLE: return 6;
2738 // True -> 7
2739 default:
2740 assert(0 && "Invalid SetCC opcode!");
2741 return 0;
2742 }
2743}
2744
2745/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2746/// opcode and two operands into either a constant true or false, or a brand new
2747/// SetCC instruction.
2748static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2749 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002750 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002751 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2752 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2753 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2754 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2755 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2756 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002757 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002758 default: assert(0 && "Illegal SetCCCode!"); return 0;
2759 }
2760}
2761
2762// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2763struct FoldSetCCLogical {
2764 InstCombiner &IC;
2765 Value *LHS, *RHS;
2766 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2767 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2768 bool shouldApply(Value *V) const {
2769 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2770 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2771 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2772 return false;
2773 }
2774 Instruction *apply(BinaryOperator &Log) const {
2775 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2776 if (SCI->getOperand(0) != LHS) {
2777 assert(SCI->getOperand(1) == LHS);
2778 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2779 }
2780
2781 unsigned LHSCode = getSetCondCode(SCI);
2782 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2783 unsigned Code;
2784 switch (Log.getOpcode()) {
2785 case Instruction::And: Code = LHSCode & RHSCode; break;
2786 case Instruction::Or: Code = LHSCode | RHSCode; break;
2787 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002788 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002789 }
2790
2791 Value *RV = getSetCCValue(Code, LHS, RHS);
2792 if (Instruction *I = dyn_cast<Instruction>(RV))
2793 return I;
2794 // Otherwise, it's a constant boolean value...
2795 return IC.ReplaceInstUsesWith(Log, RV);
2796 }
2797};
2798
Chris Lattnerba1cb382003-09-19 17:17:26 +00002799// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2800// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2801// guaranteed to be either a shift instruction or a binary operator.
2802Instruction *InstCombiner::OptAndOp(Instruction *Op,
2803 ConstantIntegral *OpRHS,
2804 ConstantIntegral *AndRHS,
2805 BinaryOperator &TheAnd) {
2806 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002807 Constant *Together = 0;
2808 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002809 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002810
Chris Lattnerba1cb382003-09-19 17:17:26 +00002811 switch (Op->getOpcode()) {
2812 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002813 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002814 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2815 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002816 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002817 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002818 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002819 }
2820 break;
2821 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002822 if (Together == AndRHS) // (X | C) & C --> C
2823 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002824
Chris Lattner86102b82005-01-01 16:22:27 +00002825 if (Op->hasOneUse() && Together != OpRHS) {
2826 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2827 std::string Op0Name = Op->getName(); Op->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2829 InsertNewInstBefore(Or, TheAnd);
2830 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002831 }
2832 break;
2833 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002834 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002835 // Adding a one to a single bit bit-field should be turned into an XOR
2836 // of the bit. First thing to check is to see if this AND is with a
2837 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002838 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002839
2840 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002841 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842
2843 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002844 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845 // Ok, at this point, we know that we are masking the result of the
2846 // ADD down to exactly one bit. If the constant we are adding has
2847 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002848 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002849
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 // Check to see if any bits below the one bit set in AndRHSV are set.
2851 if ((AddRHS & (AndRHSV-1)) == 0) {
2852 // If not, the only thing that can effect the output of the AND is
2853 // the bit specified by AndRHSV. If that bit is set, the effect of
2854 // the XOR is to toggle the bit. If it is clear, then the ADD has
2855 // no effect.
2856 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2857 TheAnd.setOperand(0, X);
2858 return &TheAnd;
2859 } else {
2860 std::string Name = Op->getName(); Op->setName("");
2861 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002862 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002863 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002864 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002865 }
2866 }
2867 }
2868 }
2869 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002870
2871 case Instruction::Shl: {
2872 // We know that the AND will not produce any of the bits shifted in, so if
2873 // the anded constant includes them, clear them now!
2874 //
2875 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002876 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2877 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002878
Chris Lattner7e794272004-09-24 15:21:34 +00002879 if (CI == ShlMask) { // Masking out bits that the shift already masks
2880 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2881 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002882 TheAnd.setOperand(1, CI);
2883 return &TheAnd;
2884 }
2885 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002886 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002887 case Instruction::LShr:
2888 {
Chris Lattner2da29172003-09-19 19:05:02 +00002889 // We know that the AND will not produce any of the bits shifted in, so if
2890 // the anded constant includes them, clear them now! This only applies to
2891 // unsigned shifts, because a signed shr may bring in set bits!
2892 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002893 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2894 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2895 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002896
Reid Spencerfdff9382006-11-08 06:47:33 +00002897 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2898 return ReplaceInstUsesWith(TheAnd, Op);
2899 } else if (CI != AndRHS) {
2900 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2901 return &TheAnd;
2902 }
2903 break;
2904 }
2905 case Instruction::AShr:
2906 // Signed shr.
2907 // See if this is shifting in some sign extension, then masking it out
2908 // with an and.
2909 if (Op->hasOneUse()) {
2910 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2911 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2912 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2913 if (CI == AndRHS) { // Masking out bits shifted in.
2914 // Make the argument unsigned.
2915 Value *ShVal = Op->getOperand(0);
2916 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2917 OpRHS, Op->getName()),
2918 TheAnd);
2919 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2920 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002921 }
Chris Lattner2da29172003-09-19 19:05:02 +00002922 }
2923 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002924 }
2925 return 0;
2926}
2927
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002928
Chris Lattner6862fbd2004-09-29 17:40:11 +00002929/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2930/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2931/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2932/// insert new instructions.
2933Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2934 bool Inside, Instruction &IB) {
2935 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2936 "Lo is not <= Hi in range emission code!");
2937 if (Inside) {
2938 if (Lo == Hi) // Trivially false.
2939 return new SetCondInst(Instruction::SetNE, V, V);
2940 if (cast<ConstantIntegral>(Lo)->isMinValue())
2941 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002942
Chris Lattner6862fbd2004-09-29 17:40:11 +00002943 Constant *AddCST = ConstantExpr::getNeg(Lo);
2944 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2945 InsertNewInstBefore(Add, IB);
2946 // Convert to unsigned for the comparison.
2947 const Type *UnsType = Add->getType()->getUnsignedVersion();
2948 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2949 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2950 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2951 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2952 }
2953
2954 if (Lo == Hi) // Trivially true.
2955 return new SetCondInst(Instruction::SetEQ, V, V);
2956
2957 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002958
2959 // V < 0 || V >= Hi ->'V > Hi-1'
2960 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961 return new SetCondInst(Instruction::SetGT, V, Hi);
2962
2963 // Emit X-Lo > Hi-Lo-1
2964 Constant *AddCST = ConstantExpr::getNeg(Lo);
2965 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2966 InsertNewInstBefore(Add, IB);
2967 // Convert to unsigned for the comparison.
2968 const Type *UnsType = Add->getType()->getUnsignedVersion();
2969 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2970 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2971 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2972 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2973}
2974
Chris Lattnerb4b25302005-09-18 07:22:02 +00002975// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2976// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2977// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2978// not, since all 1s are not contiguous.
2979static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002980 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002981 if (!isShiftedMask_64(V)) return false;
2982
2983 // look for the first zero bit after the run of ones
2984 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2985 // look for the first non-zero bit
2986 ME = 64-CountLeadingZeros_64(V);
2987 return true;
2988}
2989
2990
2991
2992/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2993/// where isSub determines whether the operator is a sub. If we can fold one of
2994/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002995///
2996/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2997/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2998/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2999///
3000/// return (A +/- B).
3001///
3002Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3003 ConstantIntegral *Mask, bool isSub,
3004 Instruction &I) {
3005 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3006 if (!LHSI || LHSI->getNumOperands() != 2 ||
3007 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3008
3009 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3010
3011 switch (LHSI->getOpcode()) {
3012 default: return 0;
3013 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003014 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3015 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003016 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003017 break;
3018
3019 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3020 // part, we don't need any explicit masks to take them out of A. If that
3021 // is all N is, ignore it.
3022 unsigned MB, ME;
3023 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003024 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3025 Mask >>= 64-MB+1;
3026 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003027 break;
3028 }
3029 }
Chris Lattneraf517572005-09-18 04:24:45 +00003030 return 0;
3031 case Instruction::Or:
3032 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003033 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003034 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003035 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003036 break;
3037 return 0;
3038 }
3039
3040 Instruction *New;
3041 if (isSub)
3042 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3043 else
3044 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3045 return InsertNewInstBefore(New, I);
3046}
3047
Chris Lattner113f4f42002-06-25 16:13:24 +00003048Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003049 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003051
Chris Lattner81a7a232004-10-16 18:11:37 +00003052 if (isa<UndefValue>(Op1)) // X & undef -> 0
3053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3054
Chris Lattner86102b82005-01-01 16:22:27 +00003055 // and X, X = X
3056 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003057 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003058
Chris Lattner5b2edb12006-02-12 08:02:11 +00003059 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003060 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003061 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003062 if (!isa<PackedType>(I.getType()) &&
3063 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003064 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003065 return &I;
3066
Chris Lattner86102b82005-01-01 16:22:27 +00003067 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003068 uint64_t AndRHSMask = AndRHS->getZExtValue();
3069 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003070 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003071
Chris Lattnerba1cb382003-09-19 17:17:26 +00003072 // Optimize a variety of ((val OP C1) & C2) combinations...
3073 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3074 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003075 Value *Op0LHS = Op0I->getOperand(0);
3076 Value *Op0RHS = Op0I->getOperand(1);
3077 switch (Op0I->getOpcode()) {
3078 case Instruction::Xor:
3079 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003080 // If the mask is only needed on one incoming arm, push it up.
3081 if (Op0I->hasOneUse()) {
3082 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3083 // Not masking anything out for the LHS, move to RHS.
3084 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3085 Op0RHS->getName()+".masked");
3086 InsertNewInstBefore(NewRHS, I);
3087 return BinaryOperator::create(
3088 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003089 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003090 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003091 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3092 // Not masking anything out for the RHS, move to LHS.
3093 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3094 Op0LHS->getName()+".masked");
3095 InsertNewInstBefore(NewLHS, I);
3096 return BinaryOperator::create(
3097 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3098 }
3099 }
3100
Chris Lattner86102b82005-01-01 16:22:27 +00003101 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003102 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003103 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3104 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3105 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3106 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3107 return BinaryOperator::createAnd(V, AndRHS);
3108 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3109 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003110 break;
3111
3112 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003113 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3114 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3115 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3116 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3117 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003118 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003119 }
3120
Chris Lattner16464b32003-07-23 19:25:52 +00003121 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003122 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003123 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003124 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3125 const Type *SrcTy = CI->getOperand(0)->getType();
3126
Chris Lattner2c14cf72005-08-07 07:03:10 +00003127 // If this is an integer truncation or change from signed-to-unsigned, and
3128 // if the source is an and/or with immediate, transform it. This
3129 // frequently occurs for bitfield accesses.
3130 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3131 if (SrcTy->getPrimitiveSizeInBits() >=
3132 I.getType()->getPrimitiveSizeInBits() &&
3133 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003134 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003135 if (CastOp->getOpcode() == Instruction::And) {
3136 // Change: and (cast (and X, C1) to T), C2
3137 // into : and (cast X to T), trunc(C1)&C2
3138 // This will folds the two ands together, which may allow other
3139 // simplifications.
3140 Instruction *NewCast =
3141 new CastInst(CastOp->getOperand(0), I.getType(),
3142 CastOp->getName()+".shrunk");
3143 NewCast = InsertNewInstBefore(NewCast, I);
3144
3145 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3146 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3147 return BinaryOperator::createAnd(NewCast, C3);
3148 } else if (CastOp->getOpcode() == Instruction::Or) {
3149 // Change: and (cast (or X, C1) to T), C2
3150 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3151 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3152 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3153 return ReplaceInstUsesWith(I, AndRHS);
3154 }
3155 }
Chris Lattner33217db2003-07-23 19:36:21 +00003156 }
Chris Lattner183b3362004-04-09 19:05:30 +00003157
3158 // Try to fold constant and into select arguments.
3159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003161 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003162 if (isa<PHINode>(Op0))
3163 if (Instruction *NV = FoldOpIntoPhi(I))
3164 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003165 }
3166
Chris Lattnerbb74e222003-03-10 23:06:50 +00003167 Value *Op0NotVal = dyn_castNotVal(Op0);
3168 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003169
Chris Lattner023a4832004-06-18 06:07:51 +00003170 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3171 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3172
Misha Brukman9c003d82004-07-30 12:50:08 +00003173 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003174 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003175 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3176 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003177 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003178 return BinaryOperator::createNot(Or);
3179 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003180
3181 {
3182 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003183 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3184 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3185 return ReplaceInstUsesWith(I, Op1);
3186 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3187 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3188 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003189
3190 if (Op0->hasOneUse() &&
3191 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3192 if (A == Op1) { // (A^B)&A -> A&(A^B)
3193 I.swapOperands(); // Simplify below
3194 std::swap(Op0, Op1);
3195 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3196 cast<BinaryOperator>(Op0)->swapOperands();
3197 I.swapOperands(); // Simplify below
3198 std::swap(Op0, Op1);
3199 }
3200 }
3201 if (Op1->hasOneUse() &&
3202 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3203 if (B == Op0) { // B&(A^B) -> B&(B^A)
3204 cast<BinaryOperator>(Op1)->swapOperands();
3205 std::swap(A, B);
3206 }
3207 if (A == Op0) { // A&(A^B) -> A & ~B
3208 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3209 InsertNewInstBefore(NotB, I);
3210 return BinaryOperator::createAnd(A, NotB);
3211 }
3212 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003213 }
3214
Chris Lattner3082c5a2003-02-18 19:28:33 +00003215
Chris Lattner623826c2004-09-28 21:48:02 +00003216 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3217 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003218 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3219 return R;
3220
Chris Lattner623826c2004-09-28 21:48:02 +00003221 Value *LHSVal, *RHSVal;
3222 ConstantInt *LHSCst, *RHSCst;
3223 Instruction::BinaryOps LHSCC, RHSCC;
3224 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3225 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3226 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3227 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003228 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003229 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3230 // Ensure that the larger constant is on the RHS.
3231 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3232 SetCondInst *LHS = cast<SetCondInst>(Op0);
3233 if (cast<ConstantBool>(Cmp)->getValue()) {
3234 std::swap(LHS, RHS);
3235 std::swap(LHSCst, RHSCst);
3236 std::swap(LHSCC, RHSCC);
3237 }
3238
3239 // At this point, we know we have have two setcc instructions
3240 // comparing a value against two constants and and'ing the result
3241 // together. Because of the above check, we know that we only have
3242 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3243 // FoldSetCCLogical check above), that the two constants are not
3244 // equal.
3245 assert(LHSCst != RHSCst && "Compares not folded above?");
3246
3247 switch (LHSCC) {
3248 default: assert(0 && "Unknown integer condition code!");
3249 case Instruction::SetEQ:
3250 switch (RHSCC) {
3251 default: assert(0 && "Unknown integer condition code!");
3252 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3253 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003254 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003255 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3256 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3257 return ReplaceInstUsesWith(I, LHS);
3258 }
3259 case Instruction::SetNE:
3260 switch (RHSCC) {
3261 default: assert(0 && "Unknown integer condition code!");
3262 case Instruction::SetLT:
3263 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3264 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3265 break; // (X != 13 & X < 15) -> no change
3266 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3267 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3268 return ReplaceInstUsesWith(I, RHS);
3269 case Instruction::SetNE:
3270 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3271 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3272 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3273 LHSVal->getName()+".off");
3274 InsertNewInstBefore(Add, I);
3275 const Type *UnsType = Add->getType()->getUnsignedVersion();
3276 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3277 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3278 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3279 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3280 }
3281 break; // (X != 13 & X != 15) -> no change
3282 }
3283 break;
3284 case Instruction::SetLT:
3285 switch (RHSCC) {
3286 default: assert(0 && "Unknown integer condition code!");
3287 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3288 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003289 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003290 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3291 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3292 return ReplaceInstUsesWith(I, LHS);
3293 }
3294 case Instruction::SetGT:
3295 switch (RHSCC) {
3296 default: assert(0 && "Unknown integer condition code!");
3297 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3298 return ReplaceInstUsesWith(I, LHS);
3299 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3300 return ReplaceInstUsesWith(I, RHS);
3301 case Instruction::SetNE:
3302 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3303 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3304 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003305 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3306 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003307 }
3308 }
3309 }
3310 }
3311
Chris Lattner3af10532006-05-05 06:39:07 +00003312 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3313 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003314 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003315 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003316 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003317 // Only do this if the casts both really cause code to be generated.
3318 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3319 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003320 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3321 Op1C->getOperand(0),
3322 I.getName());
3323 InsertNewInstBefore(NewOp, I);
3324 return new CastInst(NewOp, I.getType());
3325 }
3326 }
3327
Chris Lattner113f4f42002-06-25 16:13:24 +00003328 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003329}
3330
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003331/// CollectBSwapParts - Look to see if the specified value defines a single byte
3332/// in the result. If it does, and if the specified byte hasn't been filled in
3333/// yet, fill it in and return false.
3334static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3335 Instruction *I = dyn_cast<Instruction>(V);
3336 if (I == 0) return true;
3337
3338 // If this is an or instruction, it is an inner node of the bswap.
3339 if (I->getOpcode() == Instruction::Or)
3340 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3341 CollectBSwapParts(I->getOperand(1), ByteValues);
3342
3343 // If this is a shift by a constant int, and it is "24", then its operand
3344 // defines a byte. We only handle unsigned types here.
3345 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3346 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003347 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003348 8*(ByteValues.size()-1))
3349 return true;
3350
3351 unsigned DestNo;
3352 if (I->getOpcode() == Instruction::Shl) {
3353 // X << 24 defines the top byte with the lowest of the input bytes.
3354 DestNo = ByteValues.size()-1;
3355 } else {
3356 // X >>u 24 defines the low byte with the highest of the input bytes.
3357 DestNo = 0;
3358 }
3359
3360 // If the destination byte value is already defined, the values are or'd
3361 // together, which isn't a bswap (unless it's an or of the same bits).
3362 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3363 return true;
3364 ByteValues[DestNo] = I->getOperand(0);
3365 return false;
3366 }
3367
3368 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3369 // don't have this.
3370 Value *Shift = 0, *ShiftLHS = 0;
3371 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3372 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3373 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3374 return true;
3375 Instruction *SI = cast<Instruction>(Shift);
3376
3377 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003378 if (ShiftAmt->getZExtValue() & 7 ||
3379 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003380 return true;
3381
3382 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3383 unsigned DestByte;
3384 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003385 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003386 break;
3387 // Unknown mask for bswap.
3388 if (DestByte == ByteValues.size()) return true;
3389
Reid Spencere0fc4df2006-10-20 07:07:24 +00003390 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003391 unsigned SrcByte;
3392 if (SI->getOpcode() == Instruction::Shl)
3393 SrcByte = DestByte - ShiftBytes;
3394 else
3395 SrcByte = DestByte + ShiftBytes;
3396
3397 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3398 if (SrcByte != ByteValues.size()-DestByte-1)
3399 return true;
3400
3401 // If the destination byte value is already defined, the values are or'd
3402 // together, which isn't a bswap (unless it's an or of the same bits).
3403 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3404 return true;
3405 ByteValues[DestByte] = SI->getOperand(0);
3406 return false;
3407}
3408
3409/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3410/// If so, insert the new bswap intrinsic and return it.
3411Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3412 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3413 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3414 return 0;
3415
3416 /// ByteValues - For each byte of the result, we keep track of which value
3417 /// defines each byte.
3418 std::vector<Value*> ByteValues;
3419 ByteValues.resize(I.getType()->getPrimitiveSize());
3420
3421 // Try to find all the pieces corresponding to the bswap.
3422 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3423 CollectBSwapParts(I.getOperand(1), ByteValues))
3424 return 0;
3425
3426 // Check to see if all of the bytes come from the same value.
3427 Value *V = ByteValues[0];
3428 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3429
3430 // Check to make sure that all of the bytes come from the same value.
3431 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3432 if (ByteValues[i] != V)
3433 return 0;
3434
3435 // If they do then *success* we can turn this into a bswap. Figure out what
3436 // bswap to make it into.
3437 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003438 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003439 if (I.getType() == Type::UShortTy)
3440 FnName = "llvm.bswap.i16";
3441 else if (I.getType() == Type::UIntTy)
3442 FnName = "llvm.bswap.i32";
3443 else if (I.getType() == Type::ULongTy)
3444 FnName = "llvm.bswap.i64";
3445 else
3446 assert(0 && "Unknown integer type!");
3447 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3448
3449 return new CallInst(F, V);
3450}
3451
3452
Chris Lattner113f4f42002-06-25 16:13:24 +00003453Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003454 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003456
Chris Lattner81a7a232004-10-16 18:11:37 +00003457 if (isa<UndefValue>(Op1))
3458 return ReplaceInstUsesWith(I, // X | undef -> -1
3459 ConstantIntegral::getAllOnesValue(I.getType()));
3460
Chris Lattner5b2edb12006-02-12 08:02:11 +00003461 // or X, X = X
3462 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003463 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003464
Chris Lattner5b2edb12006-02-12 08:02:11 +00003465 // See if we can simplify any instructions used by the instruction whose sole
3466 // purpose is to compute bits we don't care about.
3467 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003468 if (!isa<PackedType>(I.getType()) &&
3469 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003470 KnownZero, KnownOne))
3471 return &I;
3472
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003473 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003474 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003475 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003476 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3477 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003478 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3479 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003480 InsertNewInstBefore(Or, I);
3481 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3482 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003483
Chris Lattnerd4252a72004-07-30 07:50:03 +00003484 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3485 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3486 std::string Op0Name = Op0->getName(); Op0->setName("");
3487 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3488 InsertNewInstBefore(Or, I);
3489 return BinaryOperator::createXor(Or,
3490 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003491 }
Chris Lattner183b3362004-04-09 19:05:30 +00003492
3493 // Try to fold constant and into select arguments.
3494 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003495 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003496 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003497 if (isa<PHINode>(Op0))
3498 if (Instruction *NV = FoldOpIntoPhi(I))
3499 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003500 }
3501
Chris Lattner330628a2006-01-06 17:59:59 +00003502 Value *A = 0, *B = 0;
3503 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003504
3505 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3506 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3507 return ReplaceInstUsesWith(I, Op1);
3508 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3509 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3510 return ReplaceInstUsesWith(I, Op0);
3511
Chris Lattnerb7845d62006-07-10 20:25:24 +00003512 // (A | B) | C and A | (B | C) -> bswap if possible.
3513 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003514 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003515 match(Op1, m_Or(m_Value(), m_Value())) ||
3516 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3517 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003518 if (Instruction *BSwap = MatchBSwap(I))
3519 return BSwap;
3520 }
3521
Chris Lattnerb62f5082005-05-09 04:58:36 +00003522 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3523 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003524 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003525 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3526 Op0->setName("");
3527 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3528 }
3529
3530 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3531 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003532 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003533 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3534 Op0->setName("");
3535 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3536 }
3537
Chris Lattner15212982005-09-18 03:42:07 +00003538 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003539 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003540 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3541
3542 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3543 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3544
3545
Chris Lattner01f56c62005-09-18 06:02:59 +00003546 // If we have: ((V + N) & C1) | (V & C2)
3547 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3548 // replace with V+N.
3549 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003550 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003551 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003552 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3553 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003554 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003555 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003556 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003557 return ReplaceInstUsesWith(I, A);
3558 }
3559 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003560 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003561 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3562 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003563 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003564 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003565 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003566 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003567 }
3568 }
3569 }
Chris Lattner812aab72003-08-12 19:11:07 +00003570
Chris Lattnerd4252a72004-07-30 07:50:03 +00003571 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3572 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003573 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003574 ConstantIntegral::getAllOnesValue(I.getType()));
3575 } else {
3576 A = 0;
3577 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003578 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003579 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3580 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003581 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003582 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003583
Misha Brukman9c003d82004-07-30 12:50:08 +00003584 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003585 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3586 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3587 I.getName()+".demorgan"), I);
3588 return BinaryOperator::createNot(And);
3589 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003590 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003591
Chris Lattner3ac7c262003-08-13 20:16:26 +00003592 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003593 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003594 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3595 return R;
3596
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003597 Value *LHSVal, *RHSVal;
3598 ConstantInt *LHSCst, *RHSCst;
3599 Instruction::BinaryOps LHSCC, RHSCC;
3600 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3601 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3602 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3603 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003604 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003605 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3606 // Ensure that the larger constant is on the RHS.
3607 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3608 SetCondInst *LHS = cast<SetCondInst>(Op0);
3609 if (cast<ConstantBool>(Cmp)->getValue()) {
3610 std::swap(LHS, RHS);
3611 std::swap(LHSCst, RHSCst);
3612 std::swap(LHSCC, RHSCC);
3613 }
3614
3615 // At this point, we know we have have two setcc instructions
3616 // comparing a value against two constants and or'ing the result
3617 // together. Because of the above check, we know that we only have
3618 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3619 // FoldSetCCLogical check above), that the two constants are not
3620 // equal.
3621 assert(LHSCst != RHSCst && "Compares not folded above?");
3622
3623 switch (LHSCC) {
3624 default: assert(0 && "Unknown integer condition code!");
3625 case Instruction::SetEQ:
3626 switch (RHSCC) {
3627 default: assert(0 && "Unknown integer condition code!");
3628 case Instruction::SetEQ:
3629 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3630 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3631 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3632 LHSVal->getName()+".off");
3633 InsertNewInstBefore(Add, I);
3634 const Type *UnsType = Add->getType()->getUnsignedVersion();
3635 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3636 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3637 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3638 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3639 }
3640 break; // (X == 13 | X == 15) -> no change
3641
Chris Lattner5c219462005-04-19 06:04:18 +00003642 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3643 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003644 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3645 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3646 return ReplaceInstUsesWith(I, RHS);
3647 }
3648 break;
3649 case Instruction::SetNE:
3650 switch (RHSCC) {
3651 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003652 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3653 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3654 return ReplaceInstUsesWith(I, LHS);
3655 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003656 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003657 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003658 }
3659 break;
3660 case Instruction::SetLT:
3661 switch (RHSCC) {
3662 default: assert(0 && "Unknown integer condition code!");
3663 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3664 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003665 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3666 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003667 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3668 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3669 return ReplaceInstUsesWith(I, RHS);
3670 }
3671 break;
3672 case Instruction::SetGT:
3673 switch (RHSCC) {
3674 default: assert(0 && "Unknown integer condition code!");
3675 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3676 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3677 return ReplaceInstUsesWith(I, LHS);
3678 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3679 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003680 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003681 }
3682 }
3683 }
3684 }
Chris Lattner3af10532006-05-05 06:39:07 +00003685
3686 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3687 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003688 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003689 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003690 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003691 // Only do this if the casts both really cause code to be generated.
3692 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3693 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003694 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3695 Op1C->getOperand(0),
3696 I.getName());
3697 InsertNewInstBefore(NewOp, I);
3698 return new CastInst(NewOp, I.getType());
3699 }
3700 }
3701
Chris Lattner15212982005-09-18 03:42:07 +00003702
Chris Lattner113f4f42002-06-25 16:13:24 +00003703 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003704}
3705
Chris Lattnerc2076352004-02-16 01:20:27 +00003706// XorSelf - Implements: X ^ X --> 0
3707struct XorSelf {
3708 Value *RHS;
3709 XorSelf(Value *rhs) : RHS(rhs) {}
3710 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3711 Instruction *apply(BinaryOperator &Xor) const {
3712 return &Xor;
3713 }
3714};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003715
3716
Chris Lattner113f4f42002-06-25 16:13:24 +00003717Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003718 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003720
Chris Lattner81a7a232004-10-16 18:11:37 +00003721 if (isa<UndefValue>(Op1))
3722 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3723
Chris Lattnerc2076352004-02-16 01:20:27 +00003724 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3725 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3726 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003727 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003728 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003729
3730 // See if we can simplify any instructions used by the instruction whose sole
3731 // purpose is to compute bits we don't care about.
3732 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003733 if (!isa<PackedType>(I.getType()) &&
3734 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003735 KnownZero, KnownOne))
3736 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003737
Chris Lattner97638592003-07-23 21:37:07 +00003738 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003739 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003740 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003741 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003742 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003743 return new SetCondInst(SCI->getInverseCondition(),
3744 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003745
Chris Lattner8f2f5982003-11-05 01:06:05 +00003746 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003747 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3748 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003749 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3750 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003751 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003752 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003753 }
Chris Lattner023a4832004-06-18 06:07:51 +00003754
3755 // ~(~X & Y) --> (X | ~Y)
3756 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3757 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3758 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3759 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003760 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003761 Op0I->getOperand(1)->getName()+".not");
3762 InsertNewInstBefore(NotY, I);
3763 return BinaryOperator::createOr(Op0NotVal, NotY);
3764 }
3765 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003766
Chris Lattner97638592003-07-23 21:37:07 +00003767 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003768 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003769 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003770 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003771 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3772 return BinaryOperator::createSub(
3773 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003774 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003775 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003776 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003777 } else if (Op0I->getOpcode() == Instruction::Or) {
3778 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3779 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3780 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3781 // Anything in both C1 and C2 is known to be zero, remove it from
3782 // NewRHS.
3783 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3784 NewRHS = ConstantExpr::getAnd(NewRHS,
3785 ConstantExpr::getNot(CommonBits));
3786 WorkList.push_back(Op0I);
3787 I.setOperand(0, Op0I->getOperand(0));
3788 I.setOperand(1, NewRHS);
3789 return &I;
3790 }
Chris Lattner97638592003-07-23 21:37:07 +00003791 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003792 }
Chris Lattner183b3362004-04-09 19:05:30 +00003793
3794 // Try to fold constant and into select arguments.
3795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003797 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003798 if (isa<PHINode>(Op0))
3799 if (Instruction *NV = FoldOpIntoPhi(I))
3800 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003801 }
3802
Chris Lattnerbb74e222003-03-10 23:06:50 +00003803 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003804 if (X == Op1)
3805 return ReplaceInstUsesWith(I,
3806 ConstantIntegral::getAllOnesValue(I.getType()));
3807
Chris Lattnerbb74e222003-03-10 23:06:50 +00003808 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003809 if (X == Op0)
3810 return ReplaceInstUsesWith(I,
3811 ConstantIntegral::getAllOnesValue(I.getType()));
3812
Chris Lattnerdcd07922006-04-01 08:03:55 +00003813 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003814 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003815 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003816 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003817 I.swapOperands();
3818 std::swap(Op0, Op1);
3819 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003820 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003821 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003822 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003823 } else if (Op1I->getOpcode() == Instruction::Xor) {
3824 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3825 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3826 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3827 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003828 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3829 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3830 Op1I->swapOperands();
3831 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3832 I.swapOperands(); // Simplified below.
3833 std::swap(Op0, Op1);
3834 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003835 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003836
Chris Lattnerdcd07922006-04-01 08:03:55 +00003837 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003838 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003839 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003840 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003841 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003842 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3843 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003844 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003845 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003846 } else if (Op0I->getOpcode() == Instruction::Xor) {
3847 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3848 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3849 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3850 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003851 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3852 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3853 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003854 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3855 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003856 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3857 InsertNewInstBefore(N, I);
3858 return BinaryOperator::createAnd(N, Op1);
3859 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003860 }
3861
Chris Lattner3ac7c262003-08-13 20:16:26 +00003862 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3863 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3864 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3865 return R;
3866
Chris Lattner3af10532006-05-05 06:39:07 +00003867 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3868 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003869 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003870 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003871 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003872 // Only do this if the casts both really cause code to be generated.
3873 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3874 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003875 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3876 Op1C->getOperand(0),
3877 I.getName());
3878 InsertNewInstBefore(NewOp, I);
3879 return new CastInst(NewOp, I.getType());
3880 }
3881 }
3882
Chris Lattner113f4f42002-06-25 16:13:24 +00003883 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003884}
3885
Chris Lattner6862fbd2004-09-29 17:40:11 +00003886static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003887 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003888}
3889
3890/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3891/// overflowed for this type.
3892static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3893 ConstantInt *In2) {
3894 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3895
3896 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003897 return cast<ConstantInt>(Result)->getZExtValue() <
3898 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003899 if (isPositive(In1) != isPositive(In2))
3900 return false;
3901 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003902 return cast<ConstantInt>(Result)->getSExtValue() <
3903 cast<ConstantInt>(In1)->getSExtValue();
3904 return cast<ConstantInt>(Result)->getSExtValue() >
3905 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003906}
3907
Chris Lattner0798af32005-01-13 20:14:25 +00003908/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3909/// code necessary to compute the offset from the base pointer (without adding
3910/// in the base pointer). Return the result as a signed integer of intptr size.
3911static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3912 TargetData &TD = IC.getTargetData();
3913 gep_type_iterator GTI = gep_type_begin(GEP);
3914 const Type *UIntPtrTy = TD.getIntPtrType();
3915 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3916 Value *Result = Constant::getNullValue(SIntPtrTy);
3917
3918 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003919 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003920
Chris Lattner0798af32005-01-13 20:14:25 +00003921 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3922 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003923 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003924 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003925 SIntPtrTy);
3926 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3927 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003928 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003929 Scale = ConstantExpr::getMul(OpC, Scale);
3930 if (Constant *RC = dyn_cast<Constant>(Result))
3931 Result = ConstantExpr::getAdd(RC, Scale);
3932 else {
3933 // Emit an add instruction.
3934 Result = IC.InsertNewInstBefore(
3935 BinaryOperator::createAdd(Result, Scale,
3936 GEP->getName()+".offs"), I);
3937 }
3938 }
3939 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003940 // Convert to correct type.
3941 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3942 Op->getName()+".c"), I);
3943 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003944 // We'll let instcombine(mul) convert this to a shl if possible.
3945 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3946 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003947
3948 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003949 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003950 GEP->getName()+".offs"), I);
3951 }
3952 }
3953 return Result;
3954}
3955
3956/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3957/// else. At this point we know that the GEP is on the LHS of the comparison.
3958Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3959 Instruction::BinaryOps Cond,
3960 Instruction &I) {
3961 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003962
3963 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3964 if (isa<PointerType>(CI->getOperand(0)->getType()))
3965 RHS = CI->getOperand(0);
3966
Chris Lattner0798af32005-01-13 20:14:25 +00003967 Value *PtrBase = GEPLHS->getOperand(0);
3968 if (PtrBase == RHS) {
3969 // As an optimization, we don't actually have to compute the actual value of
3970 // OFFSET if this is a seteq or setne comparison, just return whether each
3971 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003972 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3973 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003974 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3975 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003976 bool EmitIt = true;
3977 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3978 if (isa<UndefValue>(C)) // undef index -> undef.
3979 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3980 if (C->isNullValue())
3981 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003982 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3983 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003984 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003985 return ReplaceInstUsesWith(I, // No comparison is needed here.
3986 ConstantBool::get(Cond == Instruction::SetNE));
3987 }
3988
3989 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003990 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003991 new SetCondInst(Cond, GEPLHS->getOperand(i),
3992 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3993 if (InVal == 0)
3994 InVal = Comp;
3995 else {
3996 InVal = InsertNewInstBefore(InVal, I);
3997 InsertNewInstBefore(Comp, I);
3998 if (Cond == Instruction::SetNE) // True if any are unequal
3999 InVal = BinaryOperator::createOr(InVal, Comp);
4000 else // True if all are equal
4001 InVal = BinaryOperator::createAnd(InVal, Comp);
4002 }
4003 }
4004 }
4005
4006 if (InVal)
4007 return InVal;
4008 else
4009 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4010 ConstantBool::get(Cond == Instruction::SetEQ));
4011 }
Chris Lattner0798af32005-01-13 20:14:25 +00004012
4013 // Only lower this if the setcc is the only user of the GEP or if we expect
4014 // the result to fold to a constant!
4015 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4016 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4017 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4018 return new SetCondInst(Cond, Offset,
4019 Constant::getNullValue(Offset->getType()));
4020 }
4021 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004022 // If the base pointers are different, but the indices are the same, just
4023 // compare the base pointer.
4024 if (PtrBase != GEPRHS->getOperand(0)) {
4025 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004026 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004027 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004028 if (IndicesTheSame)
4029 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4030 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4031 IndicesTheSame = false;
4032 break;
4033 }
4034
4035 // If all indices are the same, just compare the base pointers.
4036 if (IndicesTheSame)
4037 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4038 GEPRHS->getOperand(0));
4039
4040 // Otherwise, the base pointers are different and the indices are
4041 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004042 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004043 }
Chris Lattner0798af32005-01-13 20:14:25 +00004044
Chris Lattner81e84172005-01-13 22:25:21 +00004045 // If one of the GEPs has all zero indices, recurse.
4046 bool AllZeros = true;
4047 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4048 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4049 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4050 AllZeros = false;
4051 break;
4052 }
4053 if (AllZeros)
4054 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4055 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004056
4057 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004058 AllZeros = true;
4059 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4060 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4061 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4062 AllZeros = false;
4063 break;
4064 }
4065 if (AllZeros)
4066 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4067
Chris Lattner4fa89822005-01-14 00:20:05 +00004068 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4069 // If the GEPs only differ by one index, compare it.
4070 unsigned NumDifferences = 0; // Keep track of # differences.
4071 unsigned DiffOperand = 0; // The operand that differs.
4072 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4073 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004074 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4075 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004076 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004077 NumDifferences = 2;
4078 break;
4079 } else {
4080 if (NumDifferences++) break;
4081 DiffOperand = i;
4082 }
4083 }
4084
4085 if (NumDifferences == 0) // SAME GEP?
4086 return ReplaceInstUsesWith(I, // No comparison is needed here.
4087 ConstantBool::get(Cond == Instruction::SetEQ));
4088 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004089 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4090 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004091
4092 // Convert the operands to signed values to make sure to perform a
4093 // signed comparison.
4094 const Type *NewTy = LHSV->getType()->getSignedVersion();
4095 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004096 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004097 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004098 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004099 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004100 }
4101 }
4102
Chris Lattner0798af32005-01-13 20:14:25 +00004103 // Only lower this if the setcc is the only user of the GEP or if we expect
4104 // the result to fold to a constant!
4105 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4106 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4107 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4108 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4109 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4110 return new SetCondInst(Cond, L, R);
4111 }
4112 }
4113 return 0;
4114}
4115
4116
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004117Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004118 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4120 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004121
4122 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004123 if (Op0 == Op1)
4124 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004125
Chris Lattner81a7a232004-10-16 18:11:37 +00004126 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4127 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4128
Chris Lattner15ff1e12004-11-14 07:33:16 +00004129 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4130 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004131 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4132 isa<ConstantPointerNull>(Op0)) &&
4133 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004134 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004135 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4136
4137 // setcc's with boolean values can always be turned into bitwise operations
4138 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004139 switch (I.getOpcode()) {
4140 default: assert(0 && "Invalid setcc instruction!");
4141 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004142 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004143 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004144 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004145 }
Chris Lattner4456da62004-08-11 00:50:51 +00004146 case Instruction::SetNE:
4147 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004148
Chris Lattner4456da62004-08-11 00:50:51 +00004149 case Instruction::SetGT:
4150 std::swap(Op0, Op1); // Change setgt -> setlt
4151 // FALL THROUGH
4152 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4153 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4154 InsertNewInstBefore(Not, I);
4155 return BinaryOperator::createAnd(Not, Op1);
4156 }
4157 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004158 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004159 // FALL THROUGH
4160 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4161 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4162 InsertNewInstBefore(Not, I);
4163 return BinaryOperator::createOr(Not, Op1);
4164 }
4165 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004166 }
4167
Chris Lattner2dd01742004-06-09 04:24:29 +00004168 // See if we are doing a comparison between a constant and an instruction that
4169 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004171 // Check to see if we are comparing against the minimum or maximum value...
4172 if (CI->isMinValue()) {
4173 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004174 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004175 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004176 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004177 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4178 return BinaryOperator::createSetEQ(Op0, Op1);
4179 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4180 return BinaryOperator::createSetNE(Op0, Op1);
4181
4182 } else if (CI->isMaxValue()) {
4183 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004184 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004185 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004186 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004187 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4188 return BinaryOperator::createSetEQ(Op0, Op1);
4189 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4190 return BinaryOperator::createSetNE(Op0, Op1);
4191
4192 // Comparing against a value really close to min or max?
4193 } else if (isMinValuePlusOne(CI)) {
4194 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4195 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4196 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4197 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4198
4199 } else if (isMaxValueMinusOne(CI)) {
4200 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4201 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4202 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4203 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4204 }
4205
4206 // If we still have a setle or setge instruction, turn it into the
4207 // appropriate setlt or setgt instruction. Since the border cases have
4208 // already been handled above, this requires little checking.
4209 //
4210 if (I.getOpcode() == Instruction::SetLE)
4211 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4212 if (I.getOpcode() == Instruction::SetGE)
4213 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4214
Chris Lattneree0f2802006-02-12 02:07:56 +00004215
4216 // See if we can fold the comparison based on bits known to be zero or one
4217 // in the input.
4218 uint64_t KnownZero, KnownOne;
4219 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4220 KnownZero, KnownOne, 0))
4221 return &I;
4222
4223 // Given the known and unknown bits, compute a range that the LHS could be
4224 // in.
4225 if (KnownOne | KnownZero) {
4226 if (Ty->isUnsigned()) { // Unsigned comparison.
4227 uint64_t Min, Max;
4228 uint64_t RHSVal = CI->getZExtValue();
4229 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4230 Min, Max);
4231 switch (I.getOpcode()) { // LE/GE have been folded already.
4232 default: assert(0 && "Unknown setcc opcode!");
4233 case Instruction::SetEQ:
4234 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004235 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004236 break;
4237 case Instruction::SetNE:
4238 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004239 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004240 break;
4241 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004242 if (Max < RHSVal)
4243 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4244 if (Min > RHSVal)
4245 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004246 break;
4247 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004248 if (Min > RHSVal)
4249 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4250 if (Max < RHSVal)
4251 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004252 break;
4253 }
4254 } else { // Signed comparison.
4255 int64_t Min, Max;
4256 int64_t RHSVal = CI->getSExtValue();
4257 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4258 Min, Max);
4259 switch (I.getOpcode()) { // LE/GE have been folded already.
4260 default: assert(0 && "Unknown setcc opcode!");
4261 case Instruction::SetEQ:
4262 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004263 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004264 break;
4265 case Instruction::SetNE:
4266 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004267 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004268 break;
4269 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004270 if (Max < RHSVal)
4271 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4272 if (Min > RHSVal)
4273 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004274 break;
4275 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004276 if (Min > RHSVal)
4277 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4278 if (Max < RHSVal)
4279 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004280 break;
4281 }
4282 }
4283 }
4284
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004285 // Since the RHS is a constantInt (CI), if the left hand side is an
4286 // instruction, see if that instruction also has constants so that the
4287 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004288 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004289 switch (LHSI->getOpcode()) {
4290 case Instruction::And:
4291 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4292 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004293 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4294
4295 // If an operand is an AND of a truncating cast, we can widen the
4296 // and/compare to be the input width without changing the value
4297 // produced, eliminating a cast.
4298 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4299 // We can do this transformation if either the AND constant does not
4300 // have its sign bit set or if it is an equality comparison.
4301 // Extending a relational comparison when we're checking the sign
4302 // bit would not work.
4303 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4304 (I.isEquality() ||
4305 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4306 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4307 ConstantInt *NewCST;
4308 ConstantInt *NewCI;
4309 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004310 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004311 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004312 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004313 CI->getZExtValue());
4314 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004315 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004316 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004317 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004318 CI->getZExtValue());
4319 }
4320 Instruction *NewAnd =
4321 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4322 LHSI->getName());
4323 InsertNewInstBefore(NewAnd, I);
4324 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4325 }
4326 }
4327
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004328 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4329 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4330 // happens a LOT in code produced by the C front-end, for bitfield
4331 // access.
4332 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004333
4334 // Check to see if there is a noop-cast between the shift and the and.
4335 if (!Shift) {
4336 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4337 if (CI->getOperand(0)->getType()->isIntegral() &&
4338 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4339 CI->getType()->getPrimitiveSizeInBits())
4340 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4341 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004342
Reid Spencere0fc4df2006-10-20 07:07:24 +00004343 ConstantInt *ShAmt;
4344 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004345 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4346 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004347
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004348 // We can fold this as long as we can't shift unknown bits
4349 // into the mask. This can only happen with signed shift
4350 // rights, as they sign-extend.
4351 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004352 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004353 if (!CanFold) {
4354 // To test for the bad case of the signed shr, see if any
4355 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004356 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004357 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4358
Reid Spencere0fc4df2006-10-20 07:07:24 +00004359 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004360 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004361 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4362 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004363 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4364 CanFold = true;
4365 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004366
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004367 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004368 Constant *NewCst;
4369 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004370 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004371 else
4372 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004373
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004374 // Check to see if we are shifting out any of the bits being
4375 // compared.
4376 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4377 // If we shifted bits out, the fold is not going to work out.
4378 // As a special case, check to see if this means that the
4379 // result is always true or false now.
4380 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004381 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004382 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004383 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004384 } else {
4385 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004386 Constant *NewAndCST;
4387 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004388 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004389 else
4390 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4391 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004392 if (AndTy == Ty)
4393 LHSI->setOperand(0, Shift->getOperand(0));
4394 else {
4395 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4396 *Shift);
4397 LHSI->setOperand(0, NewCast);
4398 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004399 WorkList.push_back(Shift); // Shift is dead.
4400 AddUsesToWorkList(I);
4401 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004402 }
4403 }
Chris Lattner35167c32004-06-09 07:59:58 +00004404 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004405
4406 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4407 // preferable because it allows the C<<Y expression to be hoisted out
4408 // of a loop if Y is invariant and X is not.
4409 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004410 I.isEquality() && !Shift->isArithmeticShift() &&
4411 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004412 // Compute C << Y.
4413 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004414 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004415 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4416 "tmp");
4417 } else {
4418 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004419 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004420 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004421 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004422 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004423 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004424 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004425 }
4426 InsertNewInstBefore(cast<Instruction>(NS), I);
4427
4428 // If C's sign doesn't agree with the and, insert a cast now.
4429 if (NS->getType() != LHSI->getType())
4430 NS = InsertCastBefore(NS, LHSI->getType(), I);
4431
4432 Value *ShiftOp = Shift->getOperand(0);
4433 if (ShiftOp->getType() != LHSI->getType())
4434 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4435
4436 // Compute X & (C << Y).
4437 Instruction *NewAnd =
4438 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4439 InsertNewInstBefore(NewAnd, I);
4440
4441 I.setOperand(0, NewAnd);
4442 return &I;
4443 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004444 }
4445 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004446
Chris Lattner272d5ca2004-09-28 18:22:15 +00004447 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004448 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004449 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004450 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4451
4452 // Check that the shift amount is in range. If not, don't perform
4453 // undefined shifts. When the shift is visited it will be
4454 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004455 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004456 break;
4457
Chris Lattner272d5ca2004-09-28 18:22:15 +00004458 // If we are comparing against bits always shifted out, the
4459 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004460 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004461 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004462 if (Comp != CI) {// Comparing against a bit that we know is zero.
4463 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4464 Constant *Cst = ConstantBool::get(IsSetNE);
4465 return ReplaceInstUsesWith(I, Cst);
4466 }
4467
4468 if (LHSI->hasOneUse()) {
4469 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004470 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004471 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4472
4473 Constant *Mask;
4474 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004475 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004476 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004477 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004478 } else {
4479 Mask = ConstantInt::getAllOnesValue(CI->getType());
4480 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004481
Chris Lattner272d5ca2004-09-28 18:22:15 +00004482 Instruction *AndI =
4483 BinaryOperator::createAnd(LHSI->getOperand(0),
4484 Mask, LHSI->getName()+".mask");
4485 Value *And = InsertNewInstBefore(AndI, I);
4486 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004487 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004488 }
4489 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004490 }
4491 break;
4492
Reid Spencerfdff9382006-11-08 06:47:33 +00004493 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4494 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004495 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004496 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004497 // Check that the shift amount is in range. If not, don't perform
4498 // undefined shifts. When the shift is visited it will be
4499 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004500 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004501 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004502 break;
4503
Chris Lattner1023b872004-09-27 16:18:50 +00004504 // If we are comparing against bits always shifted out, the
4505 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004506 Constant *Comp;
4507 if (CI->getType()->isUnsigned())
4508 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4509 ShAmt);
4510 else
4511 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4512 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004513
Chris Lattner1023b872004-09-27 16:18:50 +00004514 if (Comp != CI) {// Comparing against a bit that we know is zero.
4515 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4516 Constant *Cst = ConstantBool::get(IsSetNE);
4517 return ReplaceInstUsesWith(I, Cst);
4518 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004519
Chris Lattner1023b872004-09-27 16:18:50 +00004520 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004521 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004522
Chris Lattner1023b872004-09-27 16:18:50 +00004523 // Otherwise strength reduce the shift into an and.
4524 uint64_t Val = ~0ULL; // All ones.
4525 Val <<= ShAmtVal; // Shift over to the right spot.
4526
4527 Constant *Mask;
4528 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004529 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004530 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004531 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004532 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004533 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004534
Chris Lattner1023b872004-09-27 16:18:50 +00004535 Instruction *AndI =
4536 BinaryOperator::createAnd(LHSI->getOperand(0),
4537 Mask, LHSI->getName()+".mask");
4538 Value *And = InsertNewInstBefore(AndI, I);
4539 return new SetCondInst(I.getOpcode(), And,
4540 ConstantExpr::getShl(CI, ShAmt));
4541 }
Chris Lattner1023b872004-09-27 16:18:50 +00004542 }
4543 }
4544 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004545
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004546 case Instruction::SDiv:
4547 case Instruction::UDiv:
4548 // Fold: setcc ([us]div X, C1), C2 -> range test
4549 // Fold this div into the comparison, producing a range check.
4550 // Determine, based on the divide type, what the range is being
4551 // checked. If there is an overflow on the low or high side, remember
4552 // it, otherwise compute the range [low, hi) bounding the new value.
4553 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004554 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004555 // FIXME: If the operand types don't match the type of the divide
4556 // then don't attempt this transform. The code below doesn't have the
4557 // logic to deal with a signed divide and an unsigned compare (and
4558 // vice versa). This is because (x /s C1) <s C2 produces different
4559 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4560 // (x /u C1) <u C2. Simply casting the operands and result won't
4561 // work. :( The if statement below tests that condition and bails
4562 // if it finds it.
4563 const Type* DivRHSTy = DivRHS->getType();
4564 unsigned DivOpCode = LHSI->getOpcode();
4565 if (I.isEquality() &&
4566 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4567 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4568 break;
4569
4570 // Initialize the variables that will indicate the nature of the
4571 // range check.
4572 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004573 ConstantInt *LoBound = 0, *HiBound = 0;
4574
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004575 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4576 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4577 // C2 (CI). By solving for X we can turn this into a range check
4578 // instead of computing a divide.
4579 ConstantInt *Prod =
4580 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004581
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004582 // Determine if the product overflows by seeing if the product is
4583 // not equal to the divide. Make sure we do the same kind of divide
4584 // as in the LHS instruction that we're folding.
4585 bool ProdOV = !DivRHS->isNullValue() &&
4586 (DivOpCode == Instruction::SDiv ?
4587 ConstantExpr::getSDiv(Prod, DivRHS) :
4588 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4589
4590 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004591 Instruction::BinaryOps Opcode = I.getOpcode();
4592
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004593 if (DivRHS->isNullValue()) {
4594 // Don't hack on divide by zeros!
4595 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004596 LoBound = Prod;
4597 LoOverflow = ProdOV;
4598 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004599 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004600 if (CI->isNullValue()) { // (X / pos) op 0
4601 // Can't overflow.
4602 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4603 HiBound = DivRHS;
4604 } else if (isPositive(CI)) { // (X / pos) op pos
4605 LoBound = Prod;
4606 LoOverflow = ProdOV;
4607 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4608 } else { // (X / pos) op neg
4609 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4610 LoOverflow = AddWithOverflow(LoBound, Prod,
4611 cast<ConstantInt>(DivRHSH));
4612 HiBound = Prod;
4613 HiOverflow = ProdOV;
4614 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004615 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004616 if (CI->isNullValue()) { // (X / neg) op 0
4617 LoBound = AddOne(DivRHS);
4618 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004619 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004620 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004621 } else if (isPositive(CI)) { // (X / neg) op pos
4622 HiOverflow = LoOverflow = ProdOV;
4623 if (!LoOverflow)
4624 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4625 HiBound = AddOne(Prod);
4626 } else { // (X / neg) op neg
4627 LoBound = Prod;
4628 LoOverflow = HiOverflow = ProdOV;
4629 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4630 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004631
Chris Lattnera92af962004-10-11 19:40:04 +00004632 // Dividing by a negate swaps the condition.
4633 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004634 }
4635
4636 if (LoBound) {
4637 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004638 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004639 default: assert(0 && "Unhandled setcc opcode!");
4640 case Instruction::SetEQ:
4641 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004642 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004643 else if (HiOverflow)
4644 return new SetCondInst(Instruction::SetGE, X, LoBound);
4645 else if (LoOverflow)
4646 return new SetCondInst(Instruction::SetLT, X, HiBound);
4647 else
4648 return InsertRangeTest(X, LoBound, HiBound, true, I);
4649 case Instruction::SetNE:
4650 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004651 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004652 else if (HiOverflow)
4653 return new SetCondInst(Instruction::SetLT, X, LoBound);
4654 else if (LoOverflow)
4655 return new SetCondInst(Instruction::SetGE, X, HiBound);
4656 else
4657 return InsertRangeTest(X, LoBound, HiBound, false, I);
4658 case Instruction::SetLT:
4659 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004660 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004661 return new SetCondInst(Instruction::SetLT, X, LoBound);
4662 case Instruction::SetGT:
4663 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004664 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004665 return new SetCondInst(Instruction::SetGE, X, HiBound);
4666 }
4667 }
4668 }
4669 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004670 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004671
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004672 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004673 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004674 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4675
Reid Spencere0fc4df2006-10-20 07:07:24 +00004676 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4677 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004678 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4679 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004680 case Instruction::SRem:
4681 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4682 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4683 BO->hasOneUse()) {
4684 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4685 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004686 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4687 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004688 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004689 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004690 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004691 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004692 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004693 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004694 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4695 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004696 if (BO->hasOneUse())
4697 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4698 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004699 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004700 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4701 // efficiently invertible, or if the add has just this one use.
4702 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004703
Chris Lattnerc992add2003-08-13 05:33:12 +00004704 if (Value *NegVal = dyn_castNegVal(BOp1))
4705 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4706 else if (Value *NegVal = dyn_castNegVal(BOp0))
4707 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004708 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004709 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4710 BO->setName("");
4711 InsertNewInstBefore(Neg, I);
4712 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4713 }
4714 }
4715 break;
4716 case Instruction::Xor:
4717 // For the xor case, we can xor two constants together, eliminating
4718 // the explicit xor.
4719 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4720 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004721 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004722
4723 // FALLTHROUGH
4724 case Instruction::Sub:
4725 // Replace (([sub|xor] A, B) != 0) with (A != B)
4726 if (CI->isNullValue())
4727 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4728 BO->getOperand(1));
4729 break;
4730
4731 case Instruction::Or:
4732 // If bits are being or'd in that are not present in the constant we
4733 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004734 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004735 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004736 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004737 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004738 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004739 break;
4740
4741 case Instruction::And:
4742 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004743 // If bits are being compared against that are and'd out, then the
4744 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004745 if (!ConstantExpr::getAnd(CI,
4746 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004747 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004748
Chris Lattner35167c32004-06-09 07:59:58 +00004749 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004750 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004751 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4752 Instruction::SetNE, Op0,
4753 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004754
Chris Lattnerc992add2003-08-13 05:33:12 +00004755 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4756 // to be a signed value as appropriate.
4757 if (isSignBit(BOC)) {
4758 Value *X = BO->getOperand(0);
4759 // If 'X' is not signed, insert a cast now...
4760 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004761 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004762 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004763 }
4764 return new SetCondInst(isSetNE ? Instruction::SetLT :
4765 Instruction::SetGE, X,
4766 Constant::getNullValue(X->getType()));
4767 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004768
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004769 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004770 if (CI->isNullValue() && isHighOnes(BOC)) {
4771 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004772 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004773
4774 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004775 if (NegX->getType()->isSigned()) {
4776 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4777 X = InsertCastBefore(X, DestTy, I);
4778 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004779 }
4780
4781 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004782 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004783 }
4784
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004785 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004786 default: break;
4787 }
4788 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004789 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004790 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004791 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4792 Value *CastOp = Cast->getOperand(0);
4793 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004794 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004795 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004796 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004797 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004798 "Source and destination signednesses should differ!");
4799 if (Cast->getType()->isSigned()) {
4800 // If this is a signed comparison, check for comparisons in the
4801 // vicinity of zero.
4802 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4803 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004804 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004805 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004806 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004807 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004808 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004809 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004810 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004811 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004812 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004813 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004814 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004815 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004816 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004817 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004818 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004819 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004820 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004821 return BinaryOperator::createSetLT(CastOp,
4822 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004823 }
4824 }
4825 }
Chris Lattnere967b342003-06-04 05:10:11 +00004826 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004827 }
4828
Chris Lattner77c32c32005-04-23 15:31:55 +00004829 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4830 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4831 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4832 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004833 case Instruction::GetElementPtr:
4834 if (RHSC->isNullValue()) {
4835 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4836 bool isAllZeros = true;
4837 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4838 if (!isa<Constant>(LHSI->getOperand(i)) ||
4839 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4840 isAllZeros = false;
4841 break;
4842 }
4843 if (isAllZeros)
4844 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4845 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4846 }
4847 break;
4848
Chris Lattner77c32c32005-04-23 15:31:55 +00004849 case Instruction::PHI:
4850 if (Instruction *NV = FoldOpIntoPhi(I))
4851 return NV;
4852 break;
4853 case Instruction::Select:
4854 // If either operand of the select is a constant, we can fold the
4855 // comparison into the select arms, which will cause one to be
4856 // constant folded and the select turned into a bitwise or.
4857 Value *Op1 = 0, *Op2 = 0;
4858 if (LHSI->hasOneUse()) {
4859 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4860 // Fold the known value into the constant operand.
4861 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4862 // Insert a new SetCC of the other select operand.
4863 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4864 LHSI->getOperand(2), RHSC,
4865 I.getName()), I);
4866 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4867 // Fold the known value into the constant operand.
4868 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4869 // Insert a new SetCC of the other select operand.
4870 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4871 LHSI->getOperand(1), RHSC,
4872 I.getName()), I);
4873 }
4874 }
Jeff Cohen82639852005-04-23 21:38:35 +00004875
Chris Lattner77c32c32005-04-23 15:31:55 +00004876 if (Op1)
4877 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4878 break;
4879 }
4880 }
4881
Chris Lattner0798af32005-01-13 20:14:25 +00004882 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4883 if (User *GEP = dyn_castGetElementPtr(Op0))
4884 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4885 return NI;
4886 if (User *GEP = dyn_castGetElementPtr(Op1))
4887 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4888 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4889 return NI;
4890
Chris Lattner16930792003-11-03 04:25:02 +00004891 // Test to see if the operands of the setcc are casted versions of other
4892 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004893 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4894 Value *CastOp0 = CI->getOperand(0);
4895 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004896 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004897 // We keep moving the cast from the left operand over to the right
4898 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004899 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004900
Chris Lattner16930792003-11-03 04:25:02 +00004901 // If operand #1 is a cast instruction, see if we can eliminate it as
4902 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004903 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4904 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004905 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004906 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004907
Chris Lattner16930792003-11-03 04:25:02 +00004908 // If Op1 is a constant, we can fold the cast into the constant.
4909 if (Op1->getType() != Op0->getType())
4910 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4911 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4912 } else {
4913 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004914 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004915 }
4916 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4917 }
4918
Chris Lattner6444c372003-11-03 05:17:03 +00004919 // Handle the special case of: setcc (cast bool to X), <cst>
4920 // This comes up when you have code like
4921 // int X = A < B;
4922 // if (X) ...
4923 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004924 // with a constant or another cast from the same type.
4925 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4926 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4927 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004928 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004929
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004930 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004931 Value *A, *B;
4932 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4933 (A == Op1 || B == Op1)) {
4934 // (A^B) == A -> B == 0
4935 Value *OtherVal = A == Op1 ? B : A;
4936 return BinaryOperator::create(I.getOpcode(), OtherVal,
4937 Constant::getNullValue(A->getType()));
4938 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4939 (A == Op0 || B == Op0)) {
4940 // A == (A^B) -> B == 0
4941 Value *OtherVal = A == Op0 ? B : A;
4942 return BinaryOperator::create(I.getOpcode(), OtherVal,
4943 Constant::getNullValue(A->getType()));
4944 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4945 // (A-B) == A -> B == 0
4946 return BinaryOperator::create(I.getOpcode(), B,
4947 Constant::getNullValue(B->getType()));
4948 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4949 // A == (A-B) -> B == 0
4950 return BinaryOperator::create(I.getOpcode(), B,
4951 Constant::getNullValue(B->getType()));
4952 }
4953 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004954 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004955}
4956
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004957// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4958// We only handle extending casts so far.
4959//
4960Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4961 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4962 const Type *SrcTy = LHSCIOp->getType();
4963 const Type *DestTy = SCI.getOperand(0)->getType();
4964 Value *RHSCIOp;
4965
4966 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004967 return 0;
4968
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004969 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4970 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4971 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4972
4973 // Is this a sign or zero extension?
4974 bool isSignSrc = SrcTy->isSigned();
4975 bool isSignDest = DestTy->isSigned();
4976
4977 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4978 // Not an extension from the same type?
4979 RHSCIOp = CI->getOperand(0);
4980 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4981 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4982 // Compute the constant that would happen if we truncated to SrcTy then
4983 // reextended to DestTy.
4984 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4985
4986 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00004987 // Make sure that src sign and dest sign match. For example,
4988 //
4989 // %A = cast short %X to uint
4990 // %B = setgt uint %A, 1330
4991 //
Devang Patel88afd002006-10-19 19:21:36 +00004992 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00004993 //
4994 // %B = setgt short %X, 1330
4995 //
4996 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00004997 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4998 // OR operation is EQ/NE.
4999 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00005000 RHSCIOp = Res;
5001 else
5002 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005003 } else {
5004 // If the value cannot be represented in the shorter type, we cannot emit
5005 // a simple comparison.
5006 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005007 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005008 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005009 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005010
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005011 // Evaluate the comparison for LT.
5012 Value *Result;
5013 if (DestTy->isSigned()) {
5014 // We're performing a signed comparison.
5015 if (isSignSrc) {
5016 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005017 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005018 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005019 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005020 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005021 } else {
5022 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005023 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005024 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005025 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005026 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005027 }
5028 } else {
5029 // We're performing an unsigned comparison.
5030 if (!isSignSrc) {
5031 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005032 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005033 } else {
5034 // We're performing an unsigned comp with a sign extended value.
5035 // This is true if the input is >= 0. [aka >s -1]
5036 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5037 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5038 NegOne, SCI.getName()), SCI);
5039 }
Reid Spencer279fa252004-11-28 21:31:15 +00005040 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005041
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005042 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005043 if (SCI.getOpcode() == Instruction::SetLT) {
5044 return ReplaceInstUsesWith(SCI, Result);
5045 } else {
5046 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5047 if (Constant *CI = dyn_cast<Constant>(Result))
5048 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5049 else
5050 return BinaryOperator::createNot(Result);
5051 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005052 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005053 } else {
5054 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005055 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005056
Chris Lattner252a8452005-06-16 03:00:08 +00005057 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005058 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5059}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005060
Chris Lattnere8d6c602003-03-10 19:16:08 +00005061Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005062 assert(I.getOperand(1)->getType() == Type::UByteTy);
5063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005064 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005065
5066 // shl X, 0 == X and shr X, 0 == X
5067 // shl 0, X == 0 and shr 0, X == 0
5068 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005069 Op0 == Constant::getNullValue(Op0->getType()))
5070 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005071
Chris Lattner81a7a232004-10-16 18:11:37 +00005072 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5073 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005074 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005075 else // undef << X -> 0 AND undef >>u X -> 0
5076 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5077 }
5078 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005079 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005080 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5081 else
5082 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5083 }
5084
Chris Lattnerd4dee402006-11-10 23:38:52 +00005085 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5086 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005087 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005088 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005089 return ReplaceInstUsesWith(I, CSI);
5090
Chris Lattner183b3362004-04-09 19:05:30 +00005091 // Try to fold constant and into select arguments.
5092 if (isa<Constant>(Op0))
5093 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005095 return R;
5096
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005097 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005098 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005099 if (MaskedValueIsZero(Op0,
5100 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005101 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005102 }
5103 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005104
Reid Spencere0fc4df2006-10-20 07:07:24 +00005105 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5106 if (CUI->getType()->isUnsigned())
5107 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5108 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005109 return 0;
5110}
5111
Reid Spencere0fc4df2006-10-20 07:07:24 +00005112Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005113 ShiftInst &I) {
5114 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005115 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5116 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005117 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005118
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005119 // See if we can simplify any instructions used by the instruction whose sole
5120 // purpose is to compute bits we don't care about.
5121 uint64_t KnownZero, KnownOne;
5122 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5123 KnownZero, KnownOne))
5124 return &I;
5125
Chris Lattner14553932006-01-06 07:12:35 +00005126 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5127 // of a signed value.
5128 //
5129 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005130 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005131 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005132 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5133 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005134 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005135 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005136 }
Chris Lattner14553932006-01-06 07:12:35 +00005137 }
5138
5139 // ((X*C1) << C2) == (X * (C1 << C2))
5140 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5141 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5142 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5143 return BinaryOperator::createMul(BO->getOperand(0),
5144 ConstantExpr::getShl(BOOp, Op1));
5145
5146 // Try to fold constant and into select arguments.
5147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5149 return R;
5150 if (isa<PHINode>(Op0))
5151 if (Instruction *NV = FoldOpIntoPhi(I))
5152 return NV;
5153
5154 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005155 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5156 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5157 Value *V1, *V2;
5158 ConstantInt *CC;
5159 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005160 default: break;
5161 case Instruction::Add:
5162 case Instruction::And:
5163 case Instruction::Or:
5164 case Instruction::Xor:
5165 // These operators commute.
5166 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005167 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5168 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005169 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005170 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005171 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005172 Op0BO->getName());
5173 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005174 Instruction *X =
5175 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5176 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005177 InsertNewInstBefore(X, I); // (X + (Y << C))
5178 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005179 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005180 return BinaryOperator::createAnd(X, C2);
5181 }
Chris Lattner14553932006-01-06 07:12:35 +00005182
Chris Lattner797dee72005-09-18 06:30:59 +00005183 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5184 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5185 match(Op0BO->getOperand(1),
5186 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005187 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005188 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005189 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005190 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005191 Op0BO->getName());
5192 InsertNewInstBefore(YS, I); // (Y << C)
5193 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005194 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005195 V1->getName()+".mask");
5196 InsertNewInstBefore(XM, I); // X & (CC << C)
5197
5198 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5199 }
Chris Lattner14553932006-01-06 07:12:35 +00005200
Chris Lattner797dee72005-09-18 06:30:59 +00005201 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005202 case Instruction::Sub:
5203 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005204 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5205 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005206 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005207 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005208 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005209 Op0BO->getName());
5210 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005211 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005212 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005213 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005214 InsertNewInstBefore(X, I); // (X + (Y << C))
5215 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005216 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005217 return BinaryOperator::createAnd(X, C2);
5218 }
Chris Lattner14553932006-01-06 07:12:35 +00005219
Chris Lattner1df0e982006-05-31 21:14:00 +00005220 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005221 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5222 match(Op0BO->getOperand(0),
5223 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005224 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005225 cast<BinaryOperator>(Op0BO->getOperand(0))
5226 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005227 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005228 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005229 Op0BO->getName());
5230 InsertNewInstBefore(YS, I); // (Y << C)
5231 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005232 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005233 V1->getName()+".mask");
5234 InsertNewInstBefore(XM, I); // X & (CC << C)
5235
Chris Lattner1df0e982006-05-31 21:14:00 +00005236 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005237 }
Chris Lattner14553932006-01-06 07:12:35 +00005238
Chris Lattner27cb9db2005-09-18 05:12:10 +00005239 break;
Chris Lattner14553932006-01-06 07:12:35 +00005240 }
5241
5242
5243 // If the operand is an bitwise operator with a constant RHS, and the
5244 // shift is the only use, we can pull it out of the shift.
5245 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5246 bool isValid = true; // Valid only for And, Or, Xor
5247 bool highBitSet = false; // Transform if high bit of constant set?
5248
5249 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005250 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005251 case Instruction::Add:
5252 isValid = isLeftShift;
5253 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005254 case Instruction::Or:
5255 case Instruction::Xor:
5256 highBitSet = false;
5257 break;
5258 case Instruction::And:
5259 highBitSet = true;
5260 break;
Chris Lattner14553932006-01-06 07:12:35 +00005261 }
5262
5263 // If this is a signed shift right, and the high bit is modified
5264 // by the logical operation, do not perform the transformation.
5265 // The highBitSet boolean indicates the value of the high bit of
5266 // the constant which would cause it to be modified for this
5267 // operation.
5268 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005269 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005270 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005271 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5272 }
5273
5274 if (isValid) {
5275 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5276
5277 Instruction *NewShift =
5278 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5279 Op0BO->getName());
5280 Op0BO->setName("");
5281 InsertNewInstBefore(NewShift, I);
5282
5283 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5284 NewRHS);
5285 }
5286 }
5287 }
5288 }
5289
Chris Lattnereb372a02006-01-06 07:52:12 +00005290 // Find out if this is a shift of a shift by a constant.
5291 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005292 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005293 ShiftOp = Op0SI;
5294 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5295 // If this is a noop-integer case of a shift instruction, use the shift.
5296 if (CI->getOperand(0)->getType()->isInteger() &&
5297 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5298 CI->getType()->getPrimitiveSizeInBits() &&
5299 isa<ShiftInst>(CI->getOperand(0))) {
5300 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5301 }
5302 }
5303
Reid Spencere0fc4df2006-10-20 07:07:24 +00005304 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005305 // Find the operands and properties of the input shift. Note that the
5306 // signedness of the input shift may differ from the current shift if there
5307 // is a noop cast between the two.
5308 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005309 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5310 ShiftOp->getType()->isSigned() :
5311 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005312 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005313
Reid Spencere0fc4df2006-10-20 07:07:24 +00005314 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005315
Reid Spencere0fc4df2006-10-20 07:07:24 +00005316 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5317 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005318
5319 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5320 if (isLeftShift == isShiftOfLeftShift) {
5321 // Do not fold these shifts if the first one is signed and the second one
5322 // is unsigned and this is a right shift. Further, don't do any folding
5323 // on them.
5324 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5325 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005326
Chris Lattnereb372a02006-01-06 07:52:12 +00005327 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5328 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5329 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005330
Chris Lattnereb372a02006-01-06 07:52:12 +00005331 Value *Op = ShiftOp->getOperand(0);
5332 if (isShiftOfSignedShift != isSignedShift)
5333 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
Reid Spencerfdff9382006-11-08 06:47:33 +00005334 ShiftInst* ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005335 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005336 if (I.getType() == ShiftResult->getType())
5337 return ShiftResult;
5338 InsertNewInstBefore(ShiftResult, I);
5339 return new CastInst(ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005340 }
5341
5342 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5343 // signed types, we can only support the (A >> c1) << c2 configuration,
5344 // because it can not turn an arbitrary bit of A into a sign bit.
5345 if (isUnsignedShift || isLeftShift) {
5346 // Calculate bitmask for what gets shifted off the edge.
5347 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5348 if (isLeftShift)
5349 C = ConstantExpr::getShl(C, ShiftAmt1C);
5350 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005351 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005352
5353 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005354 if (Op->getType() != C->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00005355 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005356
5357 Instruction *Mask =
5358 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5359 InsertNewInstBefore(Mask, I);
5360
5361 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005362 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005363 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005364 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005365 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005366 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005367 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5368 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005369 return new ShiftInst(Instruction::LShr, Mask,
5370 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005371 } else {
5372 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005373 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005374 }
5375 } else {
5376 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005377 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005378 Instruction *Shift =
5379 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005380 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005381 InsertNewInstBefore(Shift, I);
5382
5383 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5384 C = ConstantExpr::getShl(C, Op1);
5385 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5386 InsertNewInstBefore(Mask, I);
5387 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005388 }
5389 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005390 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005391 // this case, C1 == C2 and C1 is 8, 16, or 32.
5392 if (ShiftAmt1 == ShiftAmt2) {
5393 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005394 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005395 case 8 : SExtType = Type::SByteTy; break;
5396 case 16: SExtType = Type::ShortTy; break;
5397 case 32: SExtType = Type::IntTy; break;
5398 }
5399
5400 if (SExtType) {
5401 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5402 SExtType, "sext");
5403 InsertNewInstBefore(NewTrunc, I);
5404 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005405 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005406 }
Chris Lattner86102b82005-01-01 16:22:27 +00005407 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005408 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005409 return 0;
5410}
5411
Chris Lattner48a44f72002-05-02 17:06:02 +00005412
Chris Lattner8f663e82005-10-29 04:36:15 +00005413/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5414/// expression. If so, decompose it, returning some value X, such that Val is
5415/// X*Scale+Offset.
5416///
5417static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5418 unsigned &Offset) {
5419 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5421 if (CI->getType()->isUnsigned()) {
5422 Offset = CI->getZExtValue();
5423 Scale = 1;
5424 return ConstantInt::get(Type::UIntTy, 0);
5425 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005426 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5427 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005428 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5429 if (CUI->getType()->isUnsigned()) {
5430 if (I->getOpcode() == Instruction::Shl) {
5431 // This is a value scaled by '1 << the shift amt'.
5432 Scale = 1U << CUI->getZExtValue();
5433 Offset = 0;
5434 return I->getOperand(0);
5435 } else if (I->getOpcode() == Instruction::Mul) {
5436 // This value is scaled by 'CUI'.
5437 Scale = CUI->getZExtValue();
5438 Offset = 0;
5439 return I->getOperand(0);
5440 } else if (I->getOpcode() == Instruction::Add) {
5441 // We have X+C. Check to see if we really have (X*C2)+C1,
5442 // where C1 is divisible by C2.
5443 unsigned SubScale;
5444 Value *SubVal =
5445 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5446 Offset += CUI->getZExtValue();
5447 if (SubScale > 1 && (Offset % SubScale == 0)) {
5448 Scale = SubScale;
5449 return SubVal;
5450 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005451 }
5452 }
5453 }
5454 }
5455 }
5456
5457 // Otherwise, we can't look past this.
5458 Scale = 1;
5459 Offset = 0;
5460 return Val;
5461}
5462
5463
Chris Lattner216be912005-10-24 06:03:58 +00005464/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5465/// try to eliminate the cast by moving the type information into the alloc.
5466Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5467 AllocationInst &AI) {
5468 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005469 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005470
Chris Lattnerac87beb2005-10-24 06:22:12 +00005471 // Remove any uses of AI that are dead.
5472 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5473 std::vector<Instruction*> DeadUsers;
5474 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5475 Instruction *User = cast<Instruction>(*UI++);
5476 if (isInstructionTriviallyDead(User)) {
5477 while (UI != E && *UI == User)
5478 ++UI; // If this instruction uses AI more than once, don't break UI.
5479
5480 // Add operands to the worklist.
5481 AddUsesToWorkList(*User);
5482 ++NumDeadInst;
5483 DEBUG(std::cerr << "IC: DCE: " << *User);
5484
5485 User->eraseFromParent();
5486 removeFromWorkList(User);
5487 }
5488 }
5489
Chris Lattner216be912005-10-24 06:03:58 +00005490 // Get the type really allocated and the type casted to.
5491 const Type *AllocElTy = AI.getAllocatedType();
5492 const Type *CastElTy = PTy->getElementType();
5493 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005494
Chris Lattner7d190672006-10-01 19:40:58 +00005495 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5496 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005497 if (CastElTyAlign < AllocElTyAlign) return 0;
5498
Chris Lattner46705b22005-10-24 06:35:18 +00005499 // If the allocation has multiple uses, only promote it if we are strictly
5500 // increasing the alignment of the resultant allocation. If we keep it the
5501 // same, we open the door to infinite loops of various kinds.
5502 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5503
Chris Lattner216be912005-10-24 06:03:58 +00005504 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5505 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005506 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005507
Chris Lattner8270c332005-10-29 03:19:53 +00005508 // See if we can satisfy the modulus by pulling a scale out of the array
5509 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005510 unsigned ArraySizeScale, ArrayOffset;
5511 Value *NumElements = // See if the array size is a decomposable linear expr.
5512 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5513
Chris Lattner8270c332005-10-29 03:19:53 +00005514 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5515 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005516 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5517 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005518
Chris Lattner8270c332005-10-29 03:19:53 +00005519 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5520 Value *Amt = 0;
5521 if (Scale == 1) {
5522 Amt = NumElements;
5523 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005524 // If the allocation size is constant, form a constant mul expression
5525 Amt = ConstantInt::get(Type::UIntTy, Scale);
5526 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5527 Amt = ConstantExpr::getMul(
5528 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5529 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005530 else if (Scale != 1) {
5531 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5532 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005533 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005534 }
5535
Chris Lattner8f663e82005-10-29 04:36:15 +00005536 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005537 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005538 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5539 Amt = InsertNewInstBefore(Tmp, AI);
5540 }
5541
Chris Lattner216be912005-10-24 06:03:58 +00005542 std::string Name = AI.getName(); AI.setName("");
5543 AllocationInst *New;
5544 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005545 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005546 else
Nate Begeman848622f2005-11-05 09:21:28 +00005547 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005548 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005549
5550 // If the allocation has multiple uses, insert a cast and change all things
5551 // that used it to use the new cast. This will also hack on CI, but it will
5552 // die soon.
5553 if (!AI.hasOneUse()) {
5554 AddUsesToWorkList(AI);
5555 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5556 InsertNewInstBefore(NewCast, AI);
5557 AI.replaceAllUsesWith(NewCast);
5558 }
Chris Lattner216be912005-10-24 06:03:58 +00005559 return ReplaceInstUsesWith(CI, New);
5560}
5561
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005562/// CanEvaluateInDifferentType - Return true if we can take the specified value
5563/// and return it without inserting any new casts. This is used by code that
5564/// tries to decide whether promoting or shrinking integer operations to wider
5565/// or smaller types will allow us to eliminate a truncate or extend.
5566static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5567 int &NumCastsRemoved) {
5568 if (isa<Constant>(V)) return true;
5569
5570 Instruction *I = dyn_cast<Instruction>(V);
5571 if (!I || !I->hasOneUse()) return false;
5572
5573 switch (I->getOpcode()) {
5574 case Instruction::And:
5575 case Instruction::Or:
5576 case Instruction::Xor:
5577 // These operators can all arbitrarily be extended or truncated.
5578 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5579 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5580 case Instruction::Cast:
5581 // If this is a cast from the destination type, we can trivially eliminate
5582 // it, and this will remove a cast overall.
5583 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005584 // If the first operand is itself a cast, and is eliminable, do not count
5585 // this as an eliminable cast. We would prefer to eliminate those two
5586 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005587 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005588 return true;
5589
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005590 ++NumCastsRemoved;
5591 return true;
5592 }
5593 // TODO: Can handle more cases here.
5594 break;
5595 }
5596
5597 return false;
5598}
5599
5600/// EvaluateInDifferentType - Given an expression that
5601/// CanEvaluateInDifferentType returns true for, actually insert the code to
5602/// evaluate the expression.
5603Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5604 if (Constant *C = dyn_cast<Constant>(V))
5605 return ConstantExpr::getCast(C, Ty);
5606
5607 // Otherwise, it must be an instruction.
5608 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005609 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005610 switch (I->getOpcode()) {
5611 case Instruction::And:
5612 case Instruction::Or:
5613 case Instruction::Xor: {
5614 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5615 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5616 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5617 LHS, RHS, I->getName());
5618 break;
5619 }
5620 case Instruction::Cast:
5621 // If this is a cast from the destination type, return the input.
5622 if (I->getOperand(0)->getType() == Ty)
5623 return I->getOperand(0);
5624
5625 // TODO: Can handle more cases here.
5626 assert(0 && "Unreachable!");
5627 break;
5628 }
5629
5630 return InsertNewInstBefore(Res, *I);
5631}
5632
Chris Lattner216be912005-10-24 06:03:58 +00005633
Chris Lattner48a44f72002-05-02 17:06:02 +00005634// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005635//
Chris Lattner113f4f42002-06-25 16:13:24 +00005636Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005637 Value *Src = CI.getOperand(0);
5638
Chris Lattner48a44f72002-05-02 17:06:02 +00005639 // If the user is casting a value to the same type, eliminate this cast
5640 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005641 if (CI.getType() == Src->getType())
5642 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005643
Chris Lattner81a7a232004-10-16 18:11:37 +00005644 if (isa<UndefValue>(Src)) // cast undef -> undef
5645 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5646
Chris Lattner48a44f72002-05-02 17:06:02 +00005647 // If casting the result of another cast instruction, try to eliminate this
5648 // one!
5649 //
Chris Lattner86102b82005-01-01 16:22:27 +00005650 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5651 Value *A = CSrc->getOperand(0);
5652 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5653 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005654 // This instruction now refers directly to the cast's src operand. This
5655 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005656 CI.setOperand(0, CSrc->getOperand(0));
5657 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005658 }
5659
Chris Lattner650b6da2002-08-02 20:00:25 +00005660 // If this is an A->B->A cast, and we are dealing with integral types, try
5661 // to convert this into a logical 'and' instruction.
5662 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005663 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005664 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005665 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005666 CSrc->getType()->getPrimitiveSizeInBits() <
5667 CI.getType()->getPrimitiveSizeInBits()&&
5668 A->getType()->getPrimitiveSizeInBits() ==
5669 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005670 assert(CSrc->getType() != Type::ULongTy &&
5671 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005672 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005673 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005674 AndValue);
5675 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5676 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5677 if (And->getType() != CI.getType()) {
5678 And->setName(CSrc->getName()+".mask");
5679 InsertNewInstBefore(And, CI);
5680 And = new CastInst(And, CI.getType());
5681 }
5682 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005683 }
5684 }
Chris Lattner2590e512006-02-07 06:56:34 +00005685
Chris Lattner03841652004-05-25 04:29:21 +00005686 // If this is a cast to bool, turn it into the appropriate setne instruction.
5687 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005688 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005689 Constant::getNullValue(CI.getOperand(0)->getType()));
5690
Chris Lattner2590e512006-02-07 06:56:34 +00005691 // See if we can simplify any instructions used by the LHS whose sole
5692 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005693 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5694 uint64_t KnownZero, KnownOne;
5695 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5696 KnownZero, KnownOne))
5697 return &CI;
5698 }
Chris Lattner2590e512006-02-07 06:56:34 +00005699
Chris Lattnerd0d51602003-06-21 23:12:02 +00005700 // If casting the result of a getelementptr instruction with no offset, turn
5701 // this into a cast of the original pointer!
5702 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005703 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005704 bool AllZeroOperands = true;
5705 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5706 if (!isa<Constant>(GEP->getOperand(i)) ||
5707 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5708 AllZeroOperands = false;
5709 break;
5710 }
5711 if (AllZeroOperands) {
5712 CI.setOperand(0, GEP->getOperand(0));
5713 return &CI;
5714 }
5715 }
5716
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005717 // If we are casting a malloc or alloca to a pointer to a type of the same
5718 // size, rewrite the allocation instruction to allocate the "right" type.
5719 //
5720 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005721 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5722 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005723
Chris Lattner86102b82005-01-01 16:22:27 +00005724 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5725 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5726 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005727 if (isa<PHINode>(Src))
5728 if (Instruction *NV = FoldOpIntoPhi(CI))
5729 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005730
5731 // If the source and destination are pointers, and this cast is equivalent to
5732 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5733 // This can enhance SROA and other transforms that want type-safe pointers.
5734 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5735 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5736 const Type *DstTy = DstPTy->getElementType();
5737 const Type *SrcTy = SrcPTy->getElementType();
5738
5739 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5740 unsigned NumZeros = 0;
5741 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005742 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5743 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005744 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5745 ++NumZeros;
5746 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005747
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005748 // If we found a path from the src to dest, create the getelementptr now.
5749 if (SrcTy == DstTy) {
5750 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5751 return new GetElementPtrInst(Src, Idxs);
5752 }
5753 }
5754
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005755 // If the source value is an instruction with only this use, we can attempt to
5756 // propagate the cast into the instruction. Also, only handle integral types
5757 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005758 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005759 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005760 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005761
5762 int NumCastsRemoved = 0;
5763 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5764 // If this cast is a truncate, evaluting in a different type always
5765 // eliminates the cast, so it is always a win. If this is a noop-cast
5766 // this just removes a noop cast which isn't pointful, but simplifies
5767 // the code. If this is a zero-extension, we need to do an AND to
5768 // maintain the clear top-part of the computation, so we require that
5769 // the input have eliminated at least one cast. If this is a sign
5770 // extension, we insert two new casts (to do the extension) so we
5771 // require that two casts have been eliminated.
5772 bool DoXForm;
5773 switch (getCastType(Src->getType(), CI.getType())) {
5774 default: assert(0 && "Unknown cast type!");
5775 case Noop:
5776 case Truncate:
5777 DoXForm = true;
5778 break;
5779 case Zeroext:
5780 DoXForm = NumCastsRemoved >= 1;
5781 break;
5782 case Signext:
5783 DoXForm = NumCastsRemoved >= 2;
5784 break;
5785 }
5786
5787 if (DoXForm) {
5788 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5789 assert(Res->getType() == CI.getType());
5790 switch (getCastType(Src->getType(), CI.getType())) {
5791 default: assert(0 && "Unknown cast type!");
5792 case Noop:
5793 case Truncate:
5794 // Just replace this cast with the result.
5795 return ReplaceInstUsesWith(CI, Res);
5796 case Zeroext: {
5797 // We need to emit an AND to clear the high bits.
5798 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5799 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5800 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005801 Constant *C =
5802 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005803 C = ConstantExpr::getCast(C, CI.getType());
5804 return BinaryOperator::createAnd(Res, C);
5805 }
5806 case Signext:
5807 // We need to emit a cast to truncate, then a cast to sext.
5808 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5809 CI.getType());
5810 }
5811 }
5812 }
5813
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005814 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005815 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5816 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005817
5818 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5819 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5820
5821 switch (SrcI->getOpcode()) {
5822 case Instruction::Add:
5823 case Instruction::Mul:
5824 case Instruction::And:
5825 case Instruction::Or:
5826 case Instruction::Xor:
5827 // If we are discarding information, or just changing the sign, rewrite.
5828 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5829 // Don't insert two casts if they cannot be eliminated. We allow two
5830 // casts to be inserted if the sizes are the same. This could only be
5831 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005832 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5833 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005834 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5835 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5836 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5837 ->getOpcode(), Op0c, Op1c);
5838 }
5839 }
Chris Lattner72086162005-05-06 02:07:39 +00005840
5841 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5842 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005843 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005844 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5845 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5846 return BinaryOperator::createXor(New,
5847 ConstantInt::get(CI.getType(), 1));
5848 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005849 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005850 case Instruction::SDiv:
5851 case Instruction::UDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +00005852 case Instruction::SRem:
5853 case Instruction::URem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005854 // If we are just changing the sign, rewrite.
5855 if (DestBitSize == SrcBitSize) {
5856 // Don't insert two casts if they cannot be eliminated. We allow two
5857 // casts to be inserted if the sizes are the same. This could only be
5858 // converting signedness, which is a noop.
5859 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5860 !ValueRequiresCast(Op0, DestTy, TD)) {
5861 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5862 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5863 return BinaryOperator::create(
5864 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5865 }
5866 }
5867 break;
5868
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005869 case Instruction::Shl:
5870 // Allow changing the sign of the source operand. Do not allow changing
5871 // the size of the shift, UNLESS the shift amount is a constant. We
Reid Spencerfdff9382006-11-08 06:47:33 +00005872 // must not change variable sized shifts to a smaller size, because it
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005873 // is undefined to shift more bits out than exist in the value.
5874 if (DestBitSize == SrcBitSize ||
5875 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5876 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5877 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5878 }
5879 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00005880 case Instruction::AShr:
Chris Lattner87380412005-05-06 04:18:52 +00005881 // If this is a signed shr, and if all bits shifted in are about to be
5882 // truncated off, turn it into an unsigned shr to allow greater
5883 // simplifications.
Reid Spencerfdff9382006-11-08 06:47:33 +00005884 if (DestBitSize < SrcBitSize &&
Chris Lattner87380412005-05-06 04:18:52 +00005885 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005886 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005887 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005888 // Insert the new logical shift right.
5889 return new ShiftInst(Instruction::LShr, Op0, Op1);
Chris Lattner87380412005-05-06 04:18:52 +00005890 }
5891 }
5892 break;
5893
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005894 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005895 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005896 // We if we are just checking for a seteq of a single bit and casting it
5897 // to an integer. If so, shift the bit to the appropriate place then
5898 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005899 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005900 uint64_t Op1CV = Op1C->getZExtValue();
5901 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5902 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5903 // cast (X == 1) to int --> X iff X has only the low bit set.
5904 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5905 // cast (X != 0) to int --> X iff X has only the low bit set.
5906 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5907 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5908 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5909 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5910 // If Op1C some other power of two, convert:
5911 uint64_t KnownZero, KnownOne;
5912 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5913 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5914
5915 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5916 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5917 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5918 // (X&4) == 2 --> false
5919 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005920 Constant *Res = ConstantBool::get(isSetNE);
5921 Res = ConstantExpr::getCast(Res, CI.getType());
5922 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005923 }
5924
5925 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5926 Value *In = Op0;
5927 if (ShiftAmt) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005928 // Perform a logical shr by shiftamt.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005929 // Insert the shift to put the result in the low bit.
Reid Spencerfdff9382006-11-08 06:47:33 +00005930 In = InsertNewInstBefore(new ShiftInst(Instruction::LShr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005931 ConstantInt::get(Type::UByteTy, ShiftAmt),
5932 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005933 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005934
5935 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5936 Constant *One = ConstantInt::get(In->getType(), 1);
5937 In = BinaryOperator::createXor(In, One, "tmp");
5938 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005939 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005940
5941 if (CI.getType() == In->getType())
5942 return ReplaceInstUsesWith(CI, In);
5943 else
5944 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005945 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005946 }
5947 }
5948 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005949 }
5950 }
Chris Lattner99155be2006-05-25 23:24:33 +00005951
5952 if (SrcI->hasOneUse()) {
5953 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5954 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5955 // because the inputs are known to be a vector. Check to see if this is
5956 // a cast to a vector with the same # elts.
5957 if (isa<PackedType>(CI.getType()) &&
5958 cast<PackedType>(CI.getType())->getNumElements() ==
5959 SVI->getType()->getNumElements()) {
5960 CastInst *Tmp;
5961 // If either of the operands is a cast from CI.getType(), then
5962 // evaluating the shuffle in the casted destination's type will allow
5963 // us to eliminate at least one cast.
5964 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5965 Tmp->getOperand(0)->getType() == CI.getType()) ||
5966 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005967 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005968 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5969 CI.getType(), &CI);
5970 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5971 CI.getType(), &CI);
5972 // Return a new shuffle vector. Use the same element ID's, as we
5973 // know the vector types match #elts.
5974 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5975 }
5976 }
5977 }
5978 }
5979 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005980
Chris Lattner260ab202002-04-18 17:39:14 +00005981 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005982}
5983
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005984/// GetSelectFoldableOperands - We want to turn code that looks like this:
5985/// %C = or %A, %B
5986/// %D = select %cond, %C, %A
5987/// into:
5988/// %C = select %cond, %B, 0
5989/// %D = or %A, %C
5990///
5991/// Assuming that the specified instruction is an operand to the select, return
5992/// a bitmask indicating which operands of this instruction are foldable if they
5993/// equal the other incoming value of the select.
5994///
5995static unsigned GetSelectFoldableOperands(Instruction *I) {
5996 switch (I->getOpcode()) {
5997 case Instruction::Add:
5998 case Instruction::Mul:
5999 case Instruction::And:
6000 case Instruction::Or:
6001 case Instruction::Xor:
6002 return 3; // Can fold through either operand.
6003 case Instruction::Sub: // Can only fold on the amount subtracted.
6004 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006005 case Instruction::LShr:
6006 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006007 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006008 default:
6009 return 0; // Cannot fold
6010 }
6011}
6012
6013/// GetSelectFoldableConstant - For the same transformation as the previous
6014/// function, return the identity constant that goes into the select.
6015static Constant *GetSelectFoldableConstant(Instruction *I) {
6016 switch (I->getOpcode()) {
6017 default: assert(0 && "This cannot happen!"); abort();
6018 case Instruction::Add:
6019 case Instruction::Sub:
6020 case Instruction::Or:
6021 case Instruction::Xor:
6022 return Constant::getNullValue(I->getType());
6023 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006024 case Instruction::LShr:
6025 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006026 return Constant::getNullValue(Type::UByteTy);
6027 case Instruction::And:
6028 return ConstantInt::getAllOnesValue(I->getType());
6029 case Instruction::Mul:
6030 return ConstantInt::get(I->getType(), 1);
6031 }
6032}
6033
Chris Lattner411336f2005-01-19 21:50:18 +00006034/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6035/// have the same opcode and only one use each. Try to simplify this.
6036Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6037 Instruction *FI) {
6038 if (TI->getNumOperands() == 1) {
6039 // If this is a non-volatile load or a cast from the same type,
6040 // merge.
6041 if (TI->getOpcode() == Instruction::Cast) {
6042 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6043 return 0;
6044 } else {
6045 return 0; // unknown unary op.
6046 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006047
Chris Lattner411336f2005-01-19 21:50:18 +00006048 // Fold this by inserting a select from the input values.
6049 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6050 FI->getOperand(0), SI.getName()+".v");
6051 InsertNewInstBefore(NewSI, SI);
6052 return new CastInst(NewSI, TI->getType());
6053 }
6054
6055 // Only handle binary operators here.
6056 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6057 return 0;
6058
6059 // Figure out if the operations have any operands in common.
6060 Value *MatchOp, *OtherOpT, *OtherOpF;
6061 bool MatchIsOpZero;
6062 if (TI->getOperand(0) == FI->getOperand(0)) {
6063 MatchOp = TI->getOperand(0);
6064 OtherOpT = TI->getOperand(1);
6065 OtherOpF = FI->getOperand(1);
6066 MatchIsOpZero = true;
6067 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6068 MatchOp = TI->getOperand(1);
6069 OtherOpT = TI->getOperand(0);
6070 OtherOpF = FI->getOperand(0);
6071 MatchIsOpZero = false;
6072 } else if (!TI->isCommutative()) {
6073 return 0;
6074 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6075 MatchOp = TI->getOperand(0);
6076 OtherOpT = TI->getOperand(1);
6077 OtherOpF = FI->getOperand(0);
6078 MatchIsOpZero = true;
6079 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6080 MatchOp = TI->getOperand(1);
6081 OtherOpT = TI->getOperand(0);
6082 OtherOpF = FI->getOperand(1);
6083 MatchIsOpZero = true;
6084 } else {
6085 return 0;
6086 }
6087
6088 // If we reach here, they do have operations in common.
6089 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6090 OtherOpF, SI.getName()+".v");
6091 InsertNewInstBefore(NewSI, SI);
6092
6093 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6094 if (MatchIsOpZero)
6095 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6096 else
6097 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6098 } else {
6099 if (MatchIsOpZero)
6100 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6101 else
6102 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6103 }
6104}
6105
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006106Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006107 Value *CondVal = SI.getCondition();
6108 Value *TrueVal = SI.getTrueValue();
6109 Value *FalseVal = SI.getFalseValue();
6110
6111 // select true, X, Y -> X
6112 // select false, X, Y -> Y
6113 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006114 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006115
6116 // select C, X, X -> X
6117 if (TrueVal == FalseVal)
6118 return ReplaceInstUsesWith(SI, TrueVal);
6119
Chris Lattner81a7a232004-10-16 18:11:37 +00006120 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6121 return ReplaceInstUsesWith(SI, FalseVal);
6122 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6123 return ReplaceInstUsesWith(SI, TrueVal);
6124 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6125 if (isa<Constant>(TrueVal))
6126 return ReplaceInstUsesWith(SI, TrueVal);
6127 else
6128 return ReplaceInstUsesWith(SI, FalseVal);
6129 }
6130
Chris Lattner1c631e82004-04-08 04:43:23 +00006131 if (SI.getType() == Type::BoolTy)
6132 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006133 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006134 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006135 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006136 } else {
6137 // Change: A = select B, false, C --> A = and !B, C
6138 Value *NotCond =
6139 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6140 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006141 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006142 }
6143 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006144 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006145 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006146 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006147 } else {
6148 // Change: A = select B, C, true --> A = or !B, C
6149 Value *NotCond =
6150 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6151 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006152 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006153 }
6154 }
6155
Chris Lattner183b3362004-04-09 19:05:30 +00006156 // Selecting between two integer constants?
6157 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6158 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6159 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006160 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006161 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006162 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006163 // select C, 0, 1 -> cast !C to int
6164 Value *NotCond =
6165 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006166 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006167 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006168 }
Chris Lattner35167c32004-06-09 07:59:58 +00006169
Chris Lattner380c7e92006-09-20 04:44:59 +00006170 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6171
6172 // (x <s 0) ? -1 : 0 -> sra x, 31
6173 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6174 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6175 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6176 bool CanXForm = false;
6177 if (CmpCst->getType()->isSigned())
6178 CanXForm = CmpCst->isNullValue() &&
6179 IC->getOpcode() == Instruction::SetLT;
6180 else {
6181 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006182 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006183 IC->getOpcode() == Instruction::SetGT;
6184 }
6185
6186 if (CanXForm) {
6187 // The comparison constant and the result are not neccessarily the
6188 // same width. In any case, the first step to do is make sure
6189 // that X is signed.
6190 Value *X = IC->getOperand(0);
6191 if (!X->getType()->isSigned())
6192 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6193
6194 // Now that X is signed, we have to make the all ones value. Do
6195 // this by inserting a new SRA.
6196 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006197 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006198 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006199 ShAmt, "ones");
6200 InsertNewInstBefore(SRA, SI);
6201
6202 // Finally, convert to the type of the select RHS. If this is
6203 // smaller than the compare value, it will truncate the ones to
6204 // fit. If it is larger, it will sext the ones to fit.
6205 return new CastInst(SRA, SI.getType());
6206 }
6207 }
6208
6209
6210 // If one of the constants is zero (we know they can't both be) and we
6211 // have a setcc instruction with zero, and we have an 'and' with the
6212 // non-constant value, eliminate this whole mess. This corresponds to
6213 // cases like this: ((X & 27) ? 27 : 0)
6214 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006215 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006216 cast<Constant>(IC->getOperand(1))->isNullValue())
6217 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6218 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006219 isa<ConstantInt>(ICA->getOperand(1)) &&
6220 (ICA->getOperand(1) == TrueValC ||
6221 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006222 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6223 // Okay, now we know that everything is set up, we just don't
6224 // know whether we have a setne or seteq and whether the true or
6225 // false val is the zero.
6226 bool ShouldNotVal = !TrueValC->isNullValue();
6227 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6228 Value *V = ICA;
6229 if (ShouldNotVal)
6230 V = InsertNewInstBefore(BinaryOperator::create(
6231 Instruction::Xor, V, ICA->getOperand(1)), SI);
6232 return ReplaceInstUsesWith(SI, V);
6233 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006234 }
Chris Lattner533bc492004-03-30 19:37:13 +00006235 }
Chris Lattner623fba12004-04-10 22:21:27 +00006236
6237 // See if we are selecting two values based on a comparison of the two values.
6238 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6239 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6240 // Transform (X == Y) ? X : Y -> Y
6241 if (SCI->getOpcode() == Instruction::SetEQ)
6242 return ReplaceInstUsesWith(SI, FalseVal);
6243 // Transform (X != Y) ? X : Y -> X
6244 if (SCI->getOpcode() == Instruction::SetNE)
6245 return ReplaceInstUsesWith(SI, TrueVal);
6246 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6247
6248 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6249 // Transform (X == Y) ? Y : X -> X
6250 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006251 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006252 // Transform (X != Y) ? Y : X -> Y
6253 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006254 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006255 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6256 }
6257 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006258
Chris Lattnera04c9042005-01-13 22:52:24 +00006259 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6260 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6261 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006262 Instruction *AddOp = 0, *SubOp = 0;
6263
Chris Lattner411336f2005-01-19 21:50:18 +00006264 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6265 if (TI->getOpcode() == FI->getOpcode())
6266 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6267 return IV;
6268
6269 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6270 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006271 if (TI->getOpcode() == Instruction::Sub &&
6272 FI->getOpcode() == Instruction::Add) {
6273 AddOp = FI; SubOp = TI;
6274 } else if (FI->getOpcode() == Instruction::Sub &&
6275 TI->getOpcode() == Instruction::Add) {
6276 AddOp = TI; SubOp = FI;
6277 }
6278
6279 if (AddOp) {
6280 Value *OtherAddOp = 0;
6281 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6282 OtherAddOp = AddOp->getOperand(1);
6283 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6284 OtherAddOp = AddOp->getOperand(0);
6285 }
6286
6287 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006288 // So at this point we know we have (Y -> OtherAddOp):
6289 // select C, (add X, Y), (sub X, Z)
6290 Value *NegVal; // Compute -Z
6291 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6292 NegVal = ConstantExpr::getNeg(C);
6293 } else {
6294 NegVal = InsertNewInstBefore(
6295 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006296 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006297
6298 Value *NewTrueOp = OtherAddOp;
6299 Value *NewFalseOp = NegVal;
6300 if (AddOp != TI)
6301 std::swap(NewTrueOp, NewFalseOp);
6302 Instruction *NewSel =
6303 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6304
6305 NewSel = InsertNewInstBefore(NewSel, SI);
6306 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006307 }
6308 }
6309 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006310
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006311 // See if we can fold the select into one of our operands.
6312 if (SI.getType()->isInteger()) {
6313 // See the comment above GetSelectFoldableOperands for a description of the
6314 // transformation we are doing here.
6315 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6316 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6317 !isa<Constant>(FalseVal))
6318 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6319 unsigned OpToFold = 0;
6320 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6321 OpToFold = 1;
6322 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6323 OpToFold = 2;
6324 }
6325
6326 if (OpToFold) {
6327 Constant *C = GetSelectFoldableConstant(TVI);
6328 std::string Name = TVI->getName(); TVI->setName("");
6329 Instruction *NewSel =
6330 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6331 Name);
6332 InsertNewInstBefore(NewSel, SI);
6333 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6334 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6335 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6336 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6337 else {
6338 assert(0 && "Unknown instruction!!");
6339 }
6340 }
6341 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006342
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006343 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6344 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6345 !isa<Constant>(TrueVal))
6346 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6347 unsigned OpToFold = 0;
6348 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6349 OpToFold = 1;
6350 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6351 OpToFold = 2;
6352 }
6353
6354 if (OpToFold) {
6355 Constant *C = GetSelectFoldableConstant(FVI);
6356 std::string Name = FVI->getName(); FVI->setName("");
6357 Instruction *NewSel =
6358 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6359 Name);
6360 InsertNewInstBefore(NewSel, SI);
6361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6362 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6363 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6364 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6365 else {
6366 assert(0 && "Unknown instruction!!");
6367 }
6368 }
6369 }
6370 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006371
6372 if (BinaryOperator::isNot(CondVal)) {
6373 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6374 SI.setOperand(1, FalseVal);
6375 SI.setOperand(2, TrueVal);
6376 return &SI;
6377 }
6378
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006379 return 0;
6380}
6381
Chris Lattner82f2ef22006-03-06 20:18:44 +00006382/// GetKnownAlignment - If the specified pointer has an alignment that we can
6383/// determine, return it, otherwise return 0.
6384static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6385 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6386 unsigned Align = GV->getAlignment();
6387 if (Align == 0 && TD)
6388 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6389 return Align;
6390 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6391 unsigned Align = AI->getAlignment();
6392 if (Align == 0 && TD) {
6393 if (isa<AllocaInst>(AI))
6394 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6395 else if (isa<MallocInst>(AI)) {
6396 // Malloc returns maximally aligned memory.
6397 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6398 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6399 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6400 }
6401 }
6402 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006403 } else if (isa<CastInst>(V) ||
6404 (isa<ConstantExpr>(V) &&
6405 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6406 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006407 if (isa<PointerType>(CI->getOperand(0)->getType()))
6408 return GetKnownAlignment(CI->getOperand(0), TD);
6409 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006410 } else if (isa<GetElementPtrInst>(V) ||
6411 (isa<ConstantExpr>(V) &&
6412 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6413 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006414 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6415 if (BaseAlignment == 0) return 0;
6416
6417 // If all indexes are zero, it is just the alignment of the base pointer.
6418 bool AllZeroOperands = true;
6419 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6420 if (!isa<Constant>(GEPI->getOperand(i)) ||
6421 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6422 AllZeroOperands = false;
6423 break;
6424 }
6425 if (AllZeroOperands)
6426 return BaseAlignment;
6427
6428 // Otherwise, if the base alignment is >= the alignment we expect for the
6429 // base pointer type, then we know that the resultant pointer is aligned at
6430 // least as much as its type requires.
6431 if (!TD) return 0;
6432
6433 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6434 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006435 <= BaseAlignment) {
6436 const Type *GEPTy = GEPI->getType();
6437 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6438 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006439 return 0;
6440 }
6441 return 0;
6442}
6443
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006444
Chris Lattnerc66b2232006-01-13 20:11:04 +00006445/// visitCallInst - CallInst simplification. This mostly only handles folding
6446/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6447/// the heavy lifting.
6448///
Chris Lattner970c33a2003-06-19 17:00:31 +00006449Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006450 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6451 if (!II) return visitCallSite(&CI);
6452
Chris Lattner51ea1272004-02-28 05:22:00 +00006453 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6454 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006455 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006456 bool Changed = false;
6457
6458 // memmove/cpy/set of zero bytes is a noop.
6459 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6460 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6461
Chris Lattner00648e12004-10-12 04:52:52 +00006462 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006463 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006464 // Replace the instruction with just byte operations. We would
6465 // transform other cases to loads/stores, but we don't know if
6466 // alignment is sufficient.
6467 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006468 }
6469
Chris Lattner00648e12004-10-12 04:52:52 +00006470 // If we have a memmove and the source operation is a constant global,
6471 // then the source and dest pointers can't alias, so we can change this
6472 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006473 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006474 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6475 if (GVSrc->isConstant()) {
6476 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006477 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006478 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006479 Type::UIntTy)
6480 Name = "llvm.memcpy.i32";
6481 else
6482 Name = "llvm.memcpy.i64";
6483 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006484 CI.getCalledFunction()->getFunctionType());
6485 CI.setOperand(0, MemCpy);
6486 Changed = true;
6487 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006488 }
Chris Lattner00648e12004-10-12 04:52:52 +00006489
Chris Lattner82f2ef22006-03-06 20:18:44 +00006490 // If we can determine a pointer alignment that is bigger than currently
6491 // set, update the alignment.
6492 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6493 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6494 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6495 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006496 if (MI->getAlignment()->getZExtValue() < Align) {
6497 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006498 Changed = true;
6499 }
6500 } else if (isa<MemSetInst>(MI)) {
6501 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006502 if (MI->getAlignment()->getZExtValue() < Alignment) {
6503 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006504 Changed = true;
6505 }
6506 }
6507
Chris Lattnerc66b2232006-01-13 20:11:04 +00006508 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006509 } else {
6510 switch (II->getIntrinsicID()) {
6511 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006512 case Intrinsic::ppc_altivec_lvx:
6513 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006514 case Intrinsic::x86_sse_loadu_ps:
6515 case Intrinsic::x86_sse2_loadu_pd:
6516 case Intrinsic::x86_sse2_loadu_dq:
6517 // Turn PPC lvx -> load if the pointer is known aligned.
6518 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006519 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006520 Value *Ptr = InsertCastBefore(II->getOperand(1),
6521 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006522 return new LoadInst(Ptr);
6523 }
6524 break;
6525 case Intrinsic::ppc_altivec_stvx:
6526 case Intrinsic::ppc_altivec_stvxl:
6527 // Turn stvx -> store if the pointer is known aligned.
6528 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006529 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6530 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006531 return new StoreInst(II->getOperand(1), Ptr);
6532 }
6533 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006534 case Intrinsic::x86_sse_storeu_ps:
6535 case Intrinsic::x86_sse2_storeu_pd:
6536 case Intrinsic::x86_sse2_storeu_dq:
6537 case Intrinsic::x86_sse2_storel_dq:
6538 // Turn X86 storeu -> store if the pointer is known aligned.
6539 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6540 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6541 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6542 return new StoreInst(II->getOperand(2), Ptr);
6543 }
6544 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006545
6546 case Intrinsic::x86_sse_cvttss2si: {
6547 // These intrinsics only demands the 0th element of its input vector. If
6548 // we can simplify the input based on that, do so now.
6549 uint64_t UndefElts;
6550 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6551 UndefElts)) {
6552 II->setOperand(1, V);
6553 return II;
6554 }
6555 break;
6556 }
6557
Chris Lattnere79d2492006-04-06 19:19:17 +00006558 case Intrinsic::ppc_altivec_vperm:
6559 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6560 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6561 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6562
6563 // Check that all of the elements are integer constants or undefs.
6564 bool AllEltsOk = true;
6565 for (unsigned i = 0; i != 16; ++i) {
6566 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6567 !isa<UndefValue>(Mask->getOperand(i))) {
6568 AllEltsOk = false;
6569 break;
6570 }
6571 }
6572
6573 if (AllEltsOk) {
6574 // Cast the input vectors to byte vectors.
6575 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6576 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6577 Value *Result = UndefValue::get(Op0->getType());
6578
6579 // Only extract each element once.
6580 Value *ExtractedElts[32];
6581 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6582
6583 for (unsigned i = 0; i != 16; ++i) {
6584 if (isa<UndefValue>(Mask->getOperand(i)))
6585 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006586 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006587 Idx &= 31; // Match the hardware behavior.
6588
6589 if (ExtractedElts[Idx] == 0) {
6590 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006591 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006592 InsertNewInstBefore(Elt, CI);
6593 ExtractedElts[Idx] = Elt;
6594 }
6595
6596 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006597 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006598 InsertNewInstBefore(cast<Instruction>(Result), CI);
6599 }
6600 return new CastInst(Result, CI.getType());
6601 }
6602 }
6603 break;
6604
Chris Lattner503221f2006-01-13 21:28:09 +00006605 case Intrinsic::stackrestore: {
6606 // If the save is right next to the restore, remove the restore. This can
6607 // happen when variable allocas are DCE'd.
6608 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6609 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6610 BasicBlock::iterator BI = SS;
6611 if (&*++BI == II)
6612 return EraseInstFromFunction(CI);
6613 }
6614 }
6615
6616 // If the stack restore is in a return/unwind block and if there are no
6617 // allocas or calls between the restore and the return, nuke the restore.
6618 TerminatorInst *TI = II->getParent()->getTerminator();
6619 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6620 BasicBlock::iterator BI = II;
6621 bool CannotRemove = false;
6622 for (++BI; &*BI != TI; ++BI) {
6623 if (isa<AllocaInst>(BI) ||
6624 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6625 CannotRemove = true;
6626 break;
6627 }
6628 }
6629 if (!CannotRemove)
6630 return EraseInstFromFunction(CI);
6631 }
6632 break;
6633 }
6634 }
Chris Lattner00648e12004-10-12 04:52:52 +00006635 }
6636
Chris Lattnerc66b2232006-01-13 20:11:04 +00006637 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006638}
6639
6640// InvokeInst simplification
6641//
6642Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006643 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006644}
6645
Chris Lattneraec3d942003-10-07 22:32:43 +00006646// visitCallSite - Improvements for call and invoke instructions.
6647//
6648Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006649 bool Changed = false;
6650
6651 // If the callee is a constexpr cast of a function, attempt to move the cast
6652 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006653 if (transformConstExprCastCall(CS)) return 0;
6654
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006655 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006656
Chris Lattner61d9d812005-05-13 07:09:09 +00006657 if (Function *CalleeF = dyn_cast<Function>(Callee))
6658 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6659 Instruction *OldCall = CS.getInstruction();
6660 // If the call and callee calling conventions don't match, this call must
6661 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006662 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006663 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6664 if (!OldCall->use_empty())
6665 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6666 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6667 return EraseInstFromFunction(*OldCall);
6668 return 0;
6669 }
6670
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006671 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6672 // This instruction is not reachable, just remove it. We insert a store to
6673 // undef so that we know that this code is not reachable, despite the fact
6674 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006675 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006676 UndefValue::get(PointerType::get(Type::BoolTy)),
6677 CS.getInstruction());
6678
6679 if (!CS.getInstruction()->use_empty())
6680 CS.getInstruction()->
6681 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6682
6683 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6684 // Don't break the CFG, insert a dummy cond branch.
6685 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006686 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006687 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006688 return EraseInstFromFunction(*CS.getInstruction());
6689 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006690
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006691 const PointerType *PTy = cast<PointerType>(Callee->getType());
6692 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6693 if (FTy->isVarArg()) {
6694 // See if we can optimize any arguments passed through the varargs area of
6695 // the call.
6696 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6697 E = CS.arg_end(); I != E; ++I)
6698 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6699 // If this cast does not effect the value passed through the varargs
6700 // area, we can eliminate the use of the cast.
6701 Value *Op = CI->getOperand(0);
6702 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6703 *I = Op;
6704 Changed = true;
6705 }
6706 }
6707 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006708
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006709 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006710}
6711
Chris Lattner970c33a2003-06-19 17:00:31 +00006712// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6713// attempt to move the cast to the arguments of the call/invoke.
6714//
6715bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6716 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6717 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006718 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006719 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006720 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006721 Instruction *Caller = CS.getInstruction();
6722
6723 // Okay, this is a cast from a function to a different type. Unless doing so
6724 // would cause a type conversion of one of our arguments, change this call to
6725 // be a direct call with arguments casted to the appropriate types.
6726 //
6727 const FunctionType *FT = Callee->getFunctionType();
6728 const Type *OldRetTy = Caller->getType();
6729
Chris Lattner1f7942f2004-01-14 06:06:08 +00006730 // Check to see if we are changing the return type...
6731 if (OldRetTy != FT->getReturnType()) {
6732 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006733 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6734 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006735 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006736 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006737 return false; // Cannot transform this return value...
6738
6739 // If the callsite is an invoke instruction, and the return value is used by
6740 // a PHI node in a successor, we cannot change the return type of the call
6741 // because there is no place to put the cast instruction (without breaking
6742 // the critical edge). Bail out in this case.
6743 if (!Caller->use_empty())
6744 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6745 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6746 UI != E; ++UI)
6747 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6748 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006749 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006750 return false;
6751 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006752
6753 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6754 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006755
Chris Lattner970c33a2003-06-19 17:00:31 +00006756 CallSite::arg_iterator AI = CS.arg_begin();
6757 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6758 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006759 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006760 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006761 //Either we can cast directly, or we can upconvert the argument
6762 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6763 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6764 ParamTy->isSigned() == ActTy->isSigned() &&
6765 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6766 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006767 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006768 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006769 }
6770
6771 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6772 Callee->isExternal())
6773 return false; // Do not delete arguments unless we have a function body...
6774
6775 // Okay, we decided that this is a safe thing to do: go ahead and start
6776 // inserting cast instructions as necessary...
6777 std::vector<Value*> Args;
6778 Args.reserve(NumActualArgs);
6779
6780 AI = CS.arg_begin();
6781 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6782 const Type *ParamTy = FT->getParamType(i);
6783 if ((*AI)->getType() == ParamTy) {
6784 Args.push_back(*AI);
6785 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006786 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6787 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006788 }
6789 }
6790
6791 // If the function takes more arguments than the call was taking, add them
6792 // now...
6793 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6794 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6795
6796 // If we are removing arguments to the function, emit an obnoxious warning...
6797 if (FT->getNumParams() < NumActualArgs)
6798 if (!FT->isVarArg()) {
6799 std::cerr << "WARNING: While resolving call to function '"
6800 << Callee->getName() << "' arguments were dropped!\n";
6801 } else {
6802 // Add all of the arguments in their promoted form to the arg list...
6803 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6804 const Type *PTy = getPromotedType((*AI)->getType());
6805 if (PTy != (*AI)->getType()) {
6806 // Must promote to pass through va_arg area!
6807 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6808 InsertNewInstBefore(Cast, *Caller);
6809 Args.push_back(Cast);
6810 } else {
6811 Args.push_back(*AI);
6812 }
6813 }
6814 }
6815
6816 if (FT->getReturnType() == Type::VoidTy)
6817 Caller->setName(""); // Void type should not have a name...
6818
6819 Instruction *NC;
6820 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006821 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006822 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006823 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006824 } else {
6825 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006826 if (cast<CallInst>(Caller)->isTailCall())
6827 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006828 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006829 }
6830
6831 // Insert a cast of the return type as necessary...
6832 Value *NV = NC;
6833 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6834 if (NV->getType() != Type::VoidTy) {
6835 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006836
6837 // If this is an invoke instruction, we should insert it after the first
6838 // non-phi, instruction in the normal successor block.
6839 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6840 BasicBlock::iterator I = II->getNormalDest()->begin();
6841 while (isa<PHINode>(I)) ++I;
6842 InsertNewInstBefore(NC, *I);
6843 } else {
6844 // Otherwise, it's a call, just insert cast right after the call instr
6845 InsertNewInstBefore(NC, *Caller);
6846 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006847 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006848 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006849 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006850 }
6851 }
6852
6853 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6854 Caller->replaceAllUsesWith(NV);
6855 Caller->getParent()->getInstList().erase(Caller);
6856 removeFromWorkList(Caller);
6857 return true;
6858}
6859
Chris Lattnercadac0c2006-11-01 04:51:18 +00006860/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6861/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6862/// and a single binop.
6863Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6864 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006865 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6866 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006867 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00006868 Value *LHSVal = FirstInst->getOperand(0);
6869 Value *RHSVal = FirstInst->getOperand(1);
6870
6871 const Type *LHSType = LHSVal->getType();
6872 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00006873
6874 // Scan to see if all operands are the same opcode, all have one use, and all
6875 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006876 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006877 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006878 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6879 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00006880 // types or GEP's with different index types.
6881 I->getOperand(0)->getType() != LHSType ||
6882 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00006883 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00006884
6885 // Keep track of which operand needs a phi node.
6886 if (I->getOperand(0) != LHSVal) LHSVal = 0;
6887 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00006888 }
6889
Chris Lattner4f218d52006-11-08 19:42:28 +00006890 // Otherwise, this is safe to transform, determine if it is profitable.
6891
6892 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
6893 // Indexes are often folded into load/store instructions, so we don't want to
6894 // hide them behind a phi.
6895 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
6896 return 0;
6897
Chris Lattnercadac0c2006-11-01 04:51:18 +00006898 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00006899 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00006900 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00006901 if (LHSVal == 0) {
6902 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
6903 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6904 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006905 InsertNewInstBefore(NewLHS, PN);
6906 LHSVal = NewLHS;
6907 }
Chris Lattnercd62f112006-11-08 19:29:23 +00006908
6909 if (RHSVal == 0) {
6910 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
6911 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6912 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006913 InsertNewInstBefore(NewRHS, PN);
6914 RHSVal = NewRHS;
6915 }
6916
Chris Lattnercd62f112006-11-08 19:29:23 +00006917 // Add all operands to the new PHIs.
6918 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6919 if (NewLHS) {
6920 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6921 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6922 }
6923 if (NewRHS) {
6924 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6925 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6926 }
6927 }
6928
Chris Lattnercadac0c2006-11-01 04:51:18 +00006929 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00006930 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
6931 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
6932 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
6933 else {
6934 assert(isa<GetElementPtrInst>(FirstInst));
6935 return new GetElementPtrInst(LHSVal, RHSVal);
6936 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00006937}
6938
Chris Lattner14f82c72006-11-01 07:13:54 +00006939/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6940/// of the block that defines it. This means that it must be obvious the value
6941/// of the load is not changed from the point of the load to the end of the
6942/// block it is in.
6943static bool isSafeToSinkLoad(LoadInst *L) {
6944 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6945
6946 for (++BBI; BBI != E; ++BBI)
6947 if (BBI->mayWriteToMemory())
6948 return false;
6949 return true;
6950}
6951
Chris Lattner970c33a2003-06-19 17:00:31 +00006952
Chris Lattner7515cab2004-11-14 19:13:23 +00006953// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6954// operator and they all are only used by the PHI, PHI together their
6955// inputs, and do the operation once, to the result of the PHI.
6956Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6957 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6958
6959 // Scan the instruction, looking for input operations that can be folded away.
6960 // If all input operands to the phi are the same instruction (e.g. a cast from
6961 // the same type or "+42") we can pull the operation through the PHI, reducing
6962 // code size and simplifying code.
6963 Constant *ConstantOp = 0;
6964 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00006965 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00006966 if (isa<CastInst>(FirstInst)) {
6967 CastSrcTy = FirstInst->getOperand(0)->getType();
6968 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006969 // Can fold binop or shift here if the RHS is a constant, otherwise call
6970 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00006971 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006972 if (ConstantOp == 0)
6973 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00006974 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
6975 isVolatile = LI->isVolatile();
6976 // We can't sink the load if the loaded value could be modified between the
6977 // load and the PHI.
6978 if (LI->getParent() != PN.getIncomingBlock(0) ||
6979 !isSafeToSinkLoad(LI))
6980 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00006981 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00006982 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00006983 return FoldPHIArgBinOpIntoPHI(PN);
6984 // Can't handle general GEPs yet.
6985 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006986 } else {
6987 return 0; // Cannot fold this operation.
6988 }
6989
6990 // Check to see if all arguments are the same operation.
6991 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6992 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6993 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6994 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6995 return 0;
6996 if (CastSrcTy) {
6997 if (I->getOperand(0)->getType() != CastSrcTy)
6998 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00006999 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7000 // We can't sink the load if the loaded value could be modified between the
7001 // load and the PHI.
7002 if (LI->isVolatile() != isVolatile ||
7003 LI->getParent() != PN.getIncomingBlock(i) ||
7004 !isSafeToSinkLoad(LI))
7005 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007006 } else if (I->getOperand(1) != ConstantOp) {
7007 return 0;
7008 }
7009 }
7010
7011 // Okay, they are all the same operation. Create a new PHI node of the
7012 // correct type, and PHI together all of the LHS's of the instructions.
7013 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7014 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007015 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007016
7017 Value *InVal = FirstInst->getOperand(0);
7018 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007019
7020 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007021 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7022 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7023 if (NewInVal != InVal)
7024 InVal = 0;
7025 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7026 }
7027
7028 Value *PhiVal;
7029 if (InVal) {
7030 // The new PHI unions all of the same values together. This is really
7031 // common, so we handle it intelligently here for compile-time speed.
7032 PhiVal = InVal;
7033 delete NewPN;
7034 } else {
7035 InsertNewInstBefore(NewPN, PN);
7036 PhiVal = NewPN;
7037 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007038
Chris Lattner7515cab2004-11-14 19:13:23 +00007039 // Insert and return the new operation.
7040 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007041 return new CastInst(PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007042 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007043 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007044 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007045 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007046 else
7047 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007048 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007049}
Chris Lattner48a44f72002-05-02 17:06:02 +00007050
Chris Lattner71536432005-01-17 05:10:15 +00007051/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7052/// that is dead.
7053static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7054 if (PN->use_empty()) return true;
7055 if (!PN->hasOneUse()) return false;
7056
7057 // Remember this node, and if we find the cycle, return.
7058 if (!PotentiallyDeadPHIs.insert(PN).second)
7059 return true;
7060
7061 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7062 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007063
Chris Lattner71536432005-01-17 05:10:15 +00007064 return false;
7065}
7066
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007067// PHINode simplification
7068//
Chris Lattner113f4f42002-06-25 16:13:24 +00007069Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007070 // If LCSSA is around, don't mess with Phi nodes
7071 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007072
Owen Andersonae8aa642006-07-10 22:03:18 +00007073 if (Value *V = PN.hasConstantValue())
7074 return ReplaceInstUsesWith(PN, V);
7075
7076 // If the only user of this instruction is a cast instruction, and all of the
7077 // incoming values are constants, change this PHI to merge together the casted
7078 // constants.
7079 if (PN.hasOneUse())
7080 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
7081 if (CI->getType() != PN.getType()) { // noop casts will be folded
7082 bool AllConstant = true;
7083 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7084 if (!isa<Constant>(PN.getIncomingValue(i))) {
7085 AllConstant = false;
7086 break;
7087 }
7088 if (AllConstant) {
7089 // Make a new PHI with all casted values.
7090 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
7091 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
7092 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
7093 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
7094 PN.getIncomingBlock(i));
7095 }
7096
7097 // Update the cast instruction.
7098 CI->setOperand(0, New);
7099 WorkList.push_back(CI); // revisit the cast instruction to fold.
7100 WorkList.push_back(New); // Make sure to revisit the new Phi
7101 return &PN; // PN is now dead!
7102 }
7103 }
7104
7105 // If all PHI operands are the same operation, pull them through the PHI,
7106 // reducing code size.
7107 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7108 PN.getIncomingValue(0)->hasOneUse())
7109 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7110 return Result;
7111
7112 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7113 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7114 // PHI)... break the cycle.
7115 if (PN.hasOneUse())
7116 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7117 std::set<PHINode*> PotentiallyDeadPHIs;
7118 PotentiallyDeadPHIs.insert(&PN);
7119 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7120 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7121 }
7122
Chris Lattner91daeb52003-12-19 05:58:40 +00007123 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007124}
7125
Chris Lattner69193f92004-04-05 01:30:19 +00007126static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7127 Instruction *InsertPoint,
7128 InstCombiner *IC) {
7129 unsigned PS = IC->getTargetData().getPointerSize();
7130 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00007131 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7132 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00007133 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7134 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007135}
7136
Chris Lattner48a44f72002-05-02 17:06:02 +00007137
Chris Lattner113f4f42002-06-25 16:13:24 +00007138Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007139 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007140 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007141 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007142 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007143 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007144
Chris Lattner81a7a232004-10-16 18:11:37 +00007145 if (isa<UndefValue>(GEP.getOperand(0)))
7146 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7147
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007148 bool HasZeroPointerIndex = false;
7149 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7150 HasZeroPointerIndex = C->isNullValue();
7151
7152 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007153 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007154
Chris Lattner69193f92004-04-05 01:30:19 +00007155 // Eliminate unneeded casts for indices.
7156 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007157 gep_type_iterator GTI = gep_type_begin(GEP);
7158 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7159 if (isa<SequentialType>(*GTI)) {
7160 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7161 Value *Src = CI->getOperand(0);
7162 const Type *SrcTy = Src->getType();
7163 const Type *DestTy = CI->getType();
7164 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007165 if (SrcTy->getPrimitiveSizeInBits() ==
7166 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007167 // We can always eliminate a cast from ulong or long to the other.
7168 // We can always eliminate a cast from uint to int or the other on
7169 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007170 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007171 MadeChange = true;
7172 GEP.setOperand(i, Src);
7173 }
7174 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7175 SrcTy->getPrimitiveSize() == 4) {
7176 // We can always eliminate a cast from int to [u]long. We can
7177 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7178 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007179 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007180 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007181 MadeChange = true;
7182 GEP.setOperand(i, Src);
7183 }
Chris Lattner69193f92004-04-05 01:30:19 +00007184 }
7185 }
7186 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007187 // If we are using a wider index than needed for this platform, shrink it
7188 // to what we need. If the incoming value needs a cast instruction,
7189 // insert it. This explicit cast can make subsequent optimizations more
7190 // obvious.
7191 Value *Op = GEP.getOperand(i);
7192 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007193 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007194 GEP.setOperand(i, ConstantExpr::getCast(C,
7195 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007196 MadeChange = true;
7197 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007198 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007199 GEP.setOperand(i, Op);
7200 MadeChange = true;
7201 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007202
7203 // If this is a constant idx, make sure to canonicalize it to be a signed
7204 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007205 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7206 if (CUI->getType()->isUnsigned()) {
7207 GEP.setOperand(i,
7208 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7209 MadeChange = true;
7210 }
Chris Lattner69193f92004-04-05 01:30:19 +00007211 }
7212 if (MadeChange) return &GEP;
7213
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007214 // Combine Indices - If the source pointer to this getelementptr instruction
7215 // is a getelementptr instruction, combine the indices of the two
7216 // getelementptr instructions into a single instruction.
7217 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007218 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007219 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007220 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007221
7222 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007223 // Note that if our source is a gep chain itself that we wait for that
7224 // chain to be resolved before we perform this transformation. This
7225 // avoids us creating a TON of code in some cases.
7226 //
7227 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7228 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7229 return 0; // Wait until our source is folded to completion.
7230
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007231 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007232
7233 // Find out whether the last index in the source GEP is a sequential idx.
7234 bool EndsWithSequential = false;
7235 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7236 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007237 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007238
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007239 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007240 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007241 // Replace: gep (gep %P, long B), long A, ...
7242 // With: T = long A+B; gep %P, T, ...
7243 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007244 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007245 if (SO1 == Constant::getNullValue(SO1->getType())) {
7246 Sum = GO1;
7247 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7248 Sum = SO1;
7249 } else {
7250 // If they aren't the same type, convert both to an integer of the
7251 // target's pointer size.
7252 if (SO1->getType() != GO1->getType()) {
7253 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7254 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7255 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7256 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7257 } else {
7258 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007259 if (SO1->getType()->getPrimitiveSize() == PS) {
7260 // Convert GO1 to SO1's type.
7261 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7262
7263 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7264 // Convert SO1 to GO1's type.
7265 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7266 } else {
7267 const Type *PT = TD->getIntPtrType();
7268 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7269 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7270 }
7271 }
7272 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007273 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7274 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7275 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007276 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7277 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007278 }
Chris Lattner69193f92004-04-05 01:30:19 +00007279 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007280
7281 // Recycle the GEP we already have if possible.
7282 if (SrcGEPOperands.size() == 2) {
7283 GEP.setOperand(0, SrcGEPOperands[0]);
7284 GEP.setOperand(1, Sum);
7285 return &GEP;
7286 } else {
7287 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7288 SrcGEPOperands.end()-1);
7289 Indices.push_back(Sum);
7290 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7291 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007292 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007293 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007294 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007295 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007296 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7297 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007298 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7299 }
7300
7301 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007302 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007303
Chris Lattner5f667a62004-05-07 22:09:22 +00007304 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007305 // GEP of global variable. If all of the indices for this GEP are
7306 // constants, we can promote this to a constexpr instead of an instruction.
7307
7308 // Scan for nonconstants...
7309 std::vector<Constant*> Indices;
7310 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7311 for (; I != E && isa<Constant>(*I); ++I)
7312 Indices.push_back(cast<Constant>(*I));
7313
7314 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007315 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007316
7317 // Replace all uses of the GEP with the new constexpr...
7318 return ReplaceInstUsesWith(GEP, CE);
7319 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007320 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7321 if (!isa<PointerType>(X->getType())) {
7322 // Not interesting. Source pointer must be a cast from pointer.
7323 } else if (HasZeroPointerIndex) {
7324 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7325 // into : GEP [10 x ubyte]* X, long 0, ...
7326 //
7327 // This occurs when the program declares an array extern like "int X[];"
7328 //
7329 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7330 const PointerType *XTy = cast<PointerType>(X->getType());
7331 if (const ArrayType *XATy =
7332 dyn_cast<ArrayType>(XTy->getElementType()))
7333 if (const ArrayType *CATy =
7334 dyn_cast<ArrayType>(CPTy->getElementType()))
7335 if (CATy->getElementType() == XATy->getElementType()) {
7336 // At this point, we know that the cast source type is a pointer
7337 // to an array of the same type as the destination pointer
7338 // array. Because the array type is never stepped over (there
7339 // is a leading zero) we can fold the cast into this GEP.
7340 GEP.setOperand(0, X);
7341 return &GEP;
7342 }
7343 } else if (GEP.getNumOperands() == 2) {
7344 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007345 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7346 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007347 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7348 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7349 if (isa<ArrayType>(SrcElTy) &&
7350 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7351 TD->getTypeSize(ResElTy)) {
7352 Value *V = InsertNewInstBefore(
7353 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7354 GEP.getOperand(1), GEP.getName()), GEP);
7355 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007356 }
Chris Lattner2a893292005-09-13 18:36:04 +00007357
7358 // Transform things like:
7359 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7360 // (where tmp = 8*tmp2) into:
7361 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7362
7363 if (isa<ArrayType>(SrcElTy) &&
7364 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7365 uint64_t ArrayEltSize =
7366 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7367
7368 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7369 // allow either a mul, shift, or constant here.
7370 Value *NewIdx = 0;
7371 ConstantInt *Scale = 0;
7372 if (ArrayEltSize == 1) {
7373 NewIdx = GEP.getOperand(1);
7374 Scale = ConstantInt::get(NewIdx->getType(), 1);
7375 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007376 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007377 Scale = CI;
7378 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7379 if (Inst->getOpcode() == Instruction::Shl &&
7380 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007381 unsigned ShAmt =
7382 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007383 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007384 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007385 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007386 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007387 NewIdx = Inst->getOperand(0);
7388 } else if (Inst->getOpcode() == Instruction::Mul &&
7389 isa<ConstantInt>(Inst->getOperand(1))) {
7390 Scale = cast<ConstantInt>(Inst->getOperand(1));
7391 NewIdx = Inst->getOperand(0);
7392 }
7393 }
7394
7395 // If the index will be to exactly the right offset with the scale taken
7396 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007397 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007398 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007399 Scale = ConstantInt::get(Scale->getType(),
7400 Scale->getZExtValue() / ArrayEltSize);
7401 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007402 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7403 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7404 NewIdx = InsertNewInstBefore(Sc, GEP);
7405 }
7406
7407 // Insert the new GEP instruction.
7408 Instruction *Idx =
7409 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7410 NewIdx, GEP.getName());
7411 Idx = InsertNewInstBefore(Idx, GEP);
7412 return new CastInst(Idx, GEP.getType());
7413 }
7414 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007415 }
Chris Lattnerca081252001-12-14 16:52:21 +00007416 }
7417
Chris Lattnerca081252001-12-14 16:52:21 +00007418 return 0;
7419}
7420
Chris Lattner1085bdf2002-11-04 16:18:53 +00007421Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7422 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7423 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007424 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7425 const Type *NewTy =
7426 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007427 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007428
7429 // Create and insert the replacement instruction...
7430 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007431 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007432 else {
7433 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007434 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007435 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007436
7437 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007438
Chris Lattner1085bdf2002-11-04 16:18:53 +00007439 // Scan to the end of the allocation instructions, to skip over a block of
7440 // allocas if possible...
7441 //
7442 BasicBlock::iterator It = New;
7443 while (isa<AllocationInst>(*It)) ++It;
7444
7445 // Now that I is pointing to the first non-allocation-inst in the block,
7446 // insert our getelementptr instruction...
7447 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007448 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7449 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7450 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007451
7452 // Now make everything use the getelementptr instead of the original
7453 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007454 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007455 } else if (isa<UndefValue>(AI.getArraySize())) {
7456 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007457 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007458
7459 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7460 // Note that we only do this for alloca's, because malloc should allocate and
7461 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007462 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007463 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007464 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7465
Chris Lattner1085bdf2002-11-04 16:18:53 +00007466 return 0;
7467}
7468
Chris Lattner8427bff2003-12-07 01:24:23 +00007469Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7470 Value *Op = FI.getOperand(0);
7471
7472 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7473 if (CastInst *CI = dyn_cast<CastInst>(Op))
7474 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7475 FI.setOperand(0, CI->getOperand(0));
7476 return &FI;
7477 }
7478
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007479 // free undef -> unreachable.
7480 if (isa<UndefValue>(Op)) {
7481 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007482 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007483 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7484 return EraseInstFromFunction(FI);
7485 }
7486
Chris Lattnerf3a36602004-02-28 04:57:37 +00007487 // If we have 'free null' delete the instruction. This can happen in stl code
7488 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007489 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007490 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007491
Chris Lattner8427bff2003-12-07 01:24:23 +00007492 return 0;
7493}
7494
7495
Chris Lattner72684fe2005-01-31 05:51:45 +00007496/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007497static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7498 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007499 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007500
7501 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007502 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007503 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007504
Chris Lattnerebca4762006-04-02 05:37:12 +00007505 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7506 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007507 // If the source is an array, the code below will not succeed. Check to
7508 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7509 // constants.
7510 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7511 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7512 if (ASrcTy->getNumElements() != 0) {
7513 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7514 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7515 SrcTy = cast<PointerType>(CastOp->getType());
7516 SrcPTy = SrcTy->getElementType();
7517 }
7518
Chris Lattnerebca4762006-04-02 05:37:12 +00007519 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7520 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007521 // Do not allow turning this into a load of an integer, which is then
7522 // casted to a pointer, this pessimizes pointer analysis a lot.
7523 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007524 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007525 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007526
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007527 // Okay, we are casting from one integer or pointer type to another of
7528 // the same size. Instead of casting the pointer before the load, cast
7529 // the result of the loaded value.
7530 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7531 CI->getName(),
7532 LI.isVolatile()),LI);
7533 // Now cast the result of the load.
7534 return new CastInst(NewLoad, LI.getType());
7535 }
Chris Lattner35e24772004-07-13 01:49:43 +00007536 }
7537 }
7538 return 0;
7539}
7540
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007541/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007542/// from this value cannot trap. If it is not obviously safe to load from the
7543/// specified pointer, we do a quick local scan of the basic block containing
7544/// ScanFrom, to determine if the address is already accessed.
7545static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7546 // If it is an alloca or global variable, it is always safe to load from.
7547 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7548
7549 // Otherwise, be a little bit agressive by scanning the local block where we
7550 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007551 // from/to. If so, the previous load or store would have already trapped,
7552 // so there is no harm doing an extra load (also, CSE will later eliminate
7553 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007554 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7555
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007556 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007557 --BBI;
7558
7559 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7560 if (LI->getOperand(0) == V) return true;
7561 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7562 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007563
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007564 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007565 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007566}
7567
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007568Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7569 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007570
Chris Lattnera9d84e32005-05-01 04:24:53 +00007571 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007572 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007573 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7574 return Res;
7575
7576 // None of the following transforms are legal for volatile loads.
7577 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007578
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007579 if (&LI.getParent()->front() != &LI) {
7580 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007581 // If the instruction immediately before this is a store to the same
7582 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007583 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7584 if (SI->getOperand(1) == LI.getOperand(0))
7585 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007586 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7587 if (LIB->getOperand(0) == LI.getOperand(0))
7588 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007589 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007590
7591 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7592 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7593 isa<UndefValue>(GEPI->getOperand(0))) {
7594 // Insert a new store to null instruction before the load to indicate
7595 // that this code is not reachable. We do this instead of inserting
7596 // an unreachable instruction directly because we cannot modify the
7597 // CFG.
7598 new StoreInst(UndefValue::get(LI.getType()),
7599 Constant::getNullValue(Op->getType()), &LI);
7600 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7601 }
7602
Chris Lattner81a7a232004-10-16 18:11:37 +00007603 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007604 // load null/undef -> undef
7605 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007606 // Insert a new store to null instruction before the load to indicate that
7607 // this code is not reachable. We do this instead of inserting an
7608 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007609 new StoreInst(UndefValue::get(LI.getType()),
7610 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007611 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007612 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007613
Chris Lattner81a7a232004-10-16 18:11:37 +00007614 // Instcombine load (constant global) into the value loaded.
7615 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7616 if (GV->isConstant() && !GV->isExternal())
7617 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007618
Chris Lattner81a7a232004-10-16 18:11:37 +00007619 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7621 if (CE->getOpcode() == Instruction::GetElementPtr) {
7622 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7623 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007624 if (Constant *V =
7625 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007626 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007627 if (CE->getOperand(0)->isNullValue()) {
7628 // Insert a new store to null instruction before the load to indicate
7629 // that this code is not reachable. We do this instead of inserting
7630 // an unreachable instruction directly because we cannot modify the
7631 // CFG.
7632 new StoreInst(UndefValue::get(LI.getType()),
7633 Constant::getNullValue(Op->getType()), &LI);
7634 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7635 }
7636
Chris Lattner81a7a232004-10-16 18:11:37 +00007637 } else if (CE->getOpcode() == Instruction::Cast) {
7638 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7639 return Res;
7640 }
7641 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007642
Chris Lattnera9d84e32005-05-01 04:24:53 +00007643 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007644 // Change select and PHI nodes to select values instead of addresses: this
7645 // helps alias analysis out a lot, allows many others simplifications, and
7646 // exposes redundancy in the code.
7647 //
7648 // Note that we cannot do the transformation unless we know that the
7649 // introduced loads cannot trap! Something like this is valid as long as
7650 // the condition is always false: load (select bool %C, int* null, int* %G),
7651 // but it would not be valid if we transformed it to load from null
7652 // unconditionally.
7653 //
7654 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7655 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007656 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7657 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007658 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007659 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007660 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007661 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007662 return new SelectInst(SI->getCondition(), V1, V2);
7663 }
7664
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007665 // load (select (cond, null, P)) -> load P
7666 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7667 if (C->isNullValue()) {
7668 LI.setOperand(0, SI->getOperand(2));
7669 return &LI;
7670 }
7671
7672 // load (select (cond, P, null)) -> load P
7673 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7674 if (C->isNullValue()) {
7675 LI.setOperand(0, SI->getOperand(1));
7676 return &LI;
7677 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007678 }
7679 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007680 return 0;
7681}
7682
Chris Lattner72684fe2005-01-31 05:51:45 +00007683/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7684/// when possible.
7685static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7686 User *CI = cast<User>(SI.getOperand(1));
7687 Value *CastOp = CI->getOperand(0);
7688
7689 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7690 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7691 const Type *SrcPTy = SrcTy->getElementType();
7692
7693 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7694 // If the source is an array, the code below will not succeed. Check to
7695 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7696 // constants.
7697 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7698 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7699 if (ASrcTy->getNumElements() != 0) {
7700 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7701 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7702 SrcTy = cast<PointerType>(CastOp->getType());
7703 SrcPTy = SrcTy->getElementType();
7704 }
7705
7706 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007707 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007708 IC.getTargetData().getTypeSize(DestPTy)) {
7709
7710 // Okay, we are casting from one integer or pointer type to another of
7711 // the same size. Instead of casting the pointer before the store, cast
7712 // the value to be stored.
7713 Value *NewCast;
7714 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7715 NewCast = ConstantExpr::getCast(C, SrcPTy);
7716 else
7717 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7718 SrcPTy,
7719 SI.getOperand(0)->getName()+".c"), SI);
7720
7721 return new StoreInst(NewCast, CastOp);
7722 }
7723 }
7724 }
7725 return 0;
7726}
7727
Chris Lattner31f486c2005-01-31 05:36:43 +00007728Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7729 Value *Val = SI.getOperand(0);
7730 Value *Ptr = SI.getOperand(1);
7731
7732 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007733 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007734 ++NumCombined;
7735 return 0;
7736 }
7737
Chris Lattner5997cf92006-02-08 03:25:32 +00007738 // Do really simple DSE, to catch cases where there are several consequtive
7739 // stores to the same location, separated by a few arithmetic operations. This
7740 // situation often occurs with bitfield accesses.
7741 BasicBlock::iterator BBI = &SI;
7742 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7743 --ScanInsts) {
7744 --BBI;
7745
7746 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7747 // Prev store isn't volatile, and stores to the same location?
7748 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7749 ++NumDeadStore;
7750 ++BBI;
7751 EraseInstFromFunction(*PrevSI);
7752 continue;
7753 }
7754 break;
7755 }
7756
Chris Lattnerdab43b22006-05-26 19:19:20 +00007757 // If this is a load, we have to stop. However, if the loaded value is from
7758 // the pointer we're loading and is producing the pointer we're storing,
7759 // then *this* store is dead (X = load P; store X -> P).
7760 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7761 if (LI == Val && LI->getOperand(0) == Ptr) {
7762 EraseInstFromFunction(SI);
7763 ++NumCombined;
7764 return 0;
7765 }
7766 // Otherwise, this is a load from some other location. Stores before it
7767 // may not be dead.
7768 break;
7769 }
7770
Chris Lattner5997cf92006-02-08 03:25:32 +00007771 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007772 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007773 break;
7774 }
7775
7776
7777 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007778
7779 // store X, null -> turns into 'unreachable' in SimplifyCFG
7780 if (isa<ConstantPointerNull>(Ptr)) {
7781 if (!isa<UndefValue>(Val)) {
7782 SI.setOperand(0, UndefValue::get(Val->getType()));
7783 if (Instruction *U = dyn_cast<Instruction>(Val))
7784 WorkList.push_back(U); // Dropped a use.
7785 ++NumCombined;
7786 }
7787 return 0; // Do not modify these!
7788 }
7789
7790 // store undef, Ptr -> noop
7791 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007792 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007793 ++NumCombined;
7794 return 0;
7795 }
7796
Chris Lattner72684fe2005-01-31 05:51:45 +00007797 // If the pointer destination is a cast, see if we can fold the cast into the
7798 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00007799 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00007800 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7801 return Res;
7802 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7803 if (CE->getOpcode() == Instruction::Cast)
7804 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7805 return Res;
7806
Chris Lattner219175c2005-09-12 23:23:25 +00007807
7808 // If this store is the last instruction in the basic block, and if the block
7809 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007810 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007811 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7812 if (BI->isUnconditional()) {
7813 // Check to see if the successor block has exactly two incoming edges. If
7814 // so, see if the other predecessor contains a store to the same location.
7815 // if so, insert a PHI node (if needed) and move the stores down.
7816 BasicBlock *Dest = BI->getSuccessor(0);
7817
7818 pred_iterator PI = pred_begin(Dest);
7819 BasicBlock *Other = 0;
7820 if (*PI != BI->getParent())
7821 Other = *PI;
7822 ++PI;
7823 if (PI != pred_end(Dest)) {
7824 if (*PI != BI->getParent())
7825 if (Other)
7826 Other = 0;
7827 else
7828 Other = *PI;
7829 if (++PI != pred_end(Dest))
7830 Other = 0;
7831 }
7832 if (Other) { // If only one other pred...
7833 BBI = Other->getTerminator();
7834 // Make sure this other block ends in an unconditional branch and that
7835 // there is an instruction before the branch.
7836 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7837 BBI != Other->begin()) {
7838 --BBI;
7839 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7840
7841 // If this instruction is a store to the same location.
7842 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7843 // Okay, we know we can perform this transformation. Insert a PHI
7844 // node now if we need it.
7845 Value *MergedVal = OtherStore->getOperand(0);
7846 if (MergedVal != SI.getOperand(0)) {
7847 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7848 PN->reserveOperandSpace(2);
7849 PN->addIncoming(SI.getOperand(0), SI.getParent());
7850 PN->addIncoming(OtherStore->getOperand(0), Other);
7851 MergedVal = InsertNewInstBefore(PN, Dest->front());
7852 }
7853
7854 // Advance to a place where it is safe to insert the new store and
7855 // insert it.
7856 BBI = Dest->begin();
7857 while (isa<PHINode>(BBI)) ++BBI;
7858 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7859 OtherStore->isVolatile()), *BBI);
7860
7861 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007862 EraseInstFromFunction(SI);
7863 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007864 ++NumCombined;
7865 return 0;
7866 }
7867 }
7868 }
7869 }
7870
Chris Lattner31f486c2005-01-31 05:36:43 +00007871 return 0;
7872}
7873
7874
Chris Lattner9eef8a72003-06-04 04:46:00 +00007875Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7876 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007877 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007878 BasicBlock *TrueDest;
7879 BasicBlock *FalseDest;
7880 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7881 !isa<Constant>(X)) {
7882 // Swap Destinations and condition...
7883 BI.setCondition(X);
7884 BI.setSuccessor(0, FalseDest);
7885 BI.setSuccessor(1, TrueDest);
7886 return &BI;
7887 }
7888
7889 // Cannonicalize setne -> seteq
7890 Instruction::BinaryOps Op; Value *Y;
7891 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7892 TrueDest, FalseDest)))
7893 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7894 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7895 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7896 std::string Name = I->getName(); I->setName("");
7897 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7898 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007899 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007900 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007901 BI.setSuccessor(0, FalseDest);
7902 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007903 removeFromWorkList(I);
7904 I->getParent()->getInstList().erase(I);
7905 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007906 return &BI;
7907 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007908
Chris Lattner9eef8a72003-06-04 04:46:00 +00007909 return 0;
7910}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007911
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007912Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7913 Value *Cond = SI.getCondition();
7914 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7915 if (I->getOpcode() == Instruction::Add)
7916 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7917 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7918 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007919 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007920 AddRHS));
7921 SI.setOperand(0, I->getOperand(0));
7922 WorkList.push_back(I);
7923 return &SI;
7924 }
7925 }
7926 return 0;
7927}
7928
Chris Lattner6bc98652006-03-05 00:22:33 +00007929/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7930/// is to leave as a vector operation.
7931static bool CheapToScalarize(Value *V, bool isConstant) {
7932 if (isa<ConstantAggregateZero>(V))
7933 return true;
7934 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7935 if (isConstant) return true;
7936 // If all elts are the same, we can extract.
7937 Constant *Op0 = C->getOperand(0);
7938 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7939 if (C->getOperand(i) != Op0)
7940 return false;
7941 return true;
7942 }
7943 Instruction *I = dyn_cast<Instruction>(V);
7944 if (!I) return false;
7945
7946 // Insert element gets simplified to the inserted element or is deleted if
7947 // this is constant idx extract element and its a constant idx insertelt.
7948 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7949 isa<ConstantInt>(I->getOperand(2)))
7950 return true;
7951 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7952 return true;
7953 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7954 if (BO->hasOneUse() &&
7955 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7956 CheapToScalarize(BO->getOperand(1), isConstant)))
7957 return true;
7958
7959 return false;
7960}
7961
Chris Lattner12249be2006-05-25 23:48:38 +00007962/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7963/// elements into values that are larger than the #elts in the input.
7964static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7965 unsigned NElts = SVI->getType()->getNumElements();
7966 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7967 return std::vector<unsigned>(NElts, 0);
7968 if (isa<UndefValue>(SVI->getOperand(2)))
7969 return std::vector<unsigned>(NElts, 2*NElts);
7970
7971 std::vector<unsigned> Result;
7972 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7973 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7974 if (isa<UndefValue>(CP->getOperand(i)))
7975 Result.push_back(NElts*2); // undef -> 8
7976 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007977 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00007978 return Result;
7979}
7980
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007981/// FindScalarElement - Given a vector and an element number, see if the scalar
7982/// value is already around as a register, for example if it were inserted then
7983/// extracted from the vector.
7984static Value *FindScalarElement(Value *V, unsigned EltNo) {
7985 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7986 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007987 unsigned Width = PTy->getNumElements();
7988 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007989 return UndefValue::get(PTy->getElementType());
7990
7991 if (isa<UndefValue>(V))
7992 return UndefValue::get(PTy->getElementType());
7993 else if (isa<ConstantAggregateZero>(V))
7994 return Constant::getNullValue(PTy->getElementType());
7995 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7996 return CP->getOperand(EltNo);
7997 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7998 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007999 if (!isa<ConstantInt>(III->getOperand(2)))
8000 return 0;
8001 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008002
8003 // If this is an insert to the element we are looking for, return the
8004 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008005 if (EltNo == IIElt)
8006 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008007
8008 // Otherwise, the insertelement doesn't modify the value, recurse on its
8009 // vector input.
8010 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008011 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008012 unsigned InEl = getShuffleMask(SVI)[EltNo];
8013 if (InEl < Width)
8014 return FindScalarElement(SVI->getOperand(0), InEl);
8015 else if (InEl < Width*2)
8016 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8017 else
8018 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008019 }
8020
8021 // Otherwise, we don't know.
8022 return 0;
8023}
8024
Robert Bocchinoa8352962006-01-13 22:48:06 +00008025Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008026
Chris Lattner92346c32006-03-31 18:25:14 +00008027 // If packed val is undef, replace extract with scalar undef.
8028 if (isa<UndefValue>(EI.getOperand(0)))
8029 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8030
8031 // If packed val is constant 0, replace extract with scalar 0.
8032 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8033 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8034
Robert Bocchinoa8352962006-01-13 22:48:06 +00008035 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8036 // If packed val is constant with uniform operands, replace EI
8037 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008038 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008039 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008040 if (C->getOperand(i) != op0) {
8041 op0 = 0;
8042 break;
8043 }
8044 if (op0)
8045 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008046 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008047
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008048 // If extracting a specified index from the vector, see if we can recursively
8049 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008050 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008051 // This instruction only demands the single element from the input vector.
8052 // If the input vector has a single use, simplify it based on this use
8053 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008054 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008055 if (EI.getOperand(0)->hasOneUse()) {
8056 uint64_t UndefElts;
8057 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008058 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008059 UndefElts)) {
8060 EI.setOperand(0, V);
8061 return &EI;
8062 }
8063 }
8064
Reid Spencere0fc4df2006-10-20 07:07:24 +00008065 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008066 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008067 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008068
Chris Lattner83f65782006-05-25 22:53:38 +00008069 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008070 if (I->hasOneUse()) {
8071 // Push extractelement into predecessor operation if legal and
8072 // profitable to do so
8073 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008074 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8075 if (CheapToScalarize(BO, isConstantElt)) {
8076 ExtractElementInst *newEI0 =
8077 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8078 EI.getName()+".lhs");
8079 ExtractElementInst *newEI1 =
8080 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8081 EI.getName()+".rhs");
8082 InsertNewInstBefore(newEI0, EI);
8083 InsertNewInstBefore(newEI1, EI);
8084 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8085 }
Reid Spencerde46e482006-11-02 20:25:50 +00008086 } else if (isa<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008087 Value *Ptr = InsertCastBefore(I->getOperand(0),
8088 PointerType::get(EI.getType()), EI);
8089 GetElementPtrInst *GEP =
8090 new GetElementPtrInst(Ptr, EI.getOperand(1),
8091 I->getName() + ".gep");
8092 InsertNewInstBefore(GEP, EI);
8093 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008094 }
8095 }
8096 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8097 // Extracting the inserted element?
8098 if (IE->getOperand(2) == EI.getOperand(1))
8099 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8100 // If the inserted and extracted elements are constants, they must not
8101 // be the same value, extract from the pre-inserted value instead.
8102 if (isa<Constant>(IE->getOperand(2)) &&
8103 isa<Constant>(EI.getOperand(1))) {
8104 AddUsesToWorkList(EI);
8105 EI.setOperand(0, IE->getOperand(0));
8106 return &EI;
8107 }
8108 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8109 // If this is extracting an element from a shufflevector, figure out where
8110 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008111 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8112 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008113 Value *Src;
8114 if (SrcIdx < SVI->getType()->getNumElements())
8115 Src = SVI->getOperand(0);
8116 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8117 SrcIdx -= SVI->getType()->getNumElements();
8118 Src = SVI->getOperand(1);
8119 } else {
8120 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008121 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008122 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008123 }
8124 }
Chris Lattner83f65782006-05-25 22:53:38 +00008125 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008126 return 0;
8127}
8128
Chris Lattner90951862006-04-16 00:51:47 +00008129/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8130/// elements from either LHS or RHS, return the shuffle mask and true.
8131/// Otherwise, return false.
8132static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8133 std::vector<Constant*> &Mask) {
8134 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8135 "Invalid CollectSingleShuffleElements");
8136 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8137
8138 if (isa<UndefValue>(V)) {
8139 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8140 return true;
8141 } else if (V == LHS) {
8142 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008143 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008144 return true;
8145 } else if (V == RHS) {
8146 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008147 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008148 return true;
8149 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8150 // If this is an insert of an extract from some other vector, include it.
8151 Value *VecOp = IEI->getOperand(0);
8152 Value *ScalarOp = IEI->getOperand(1);
8153 Value *IdxOp = IEI->getOperand(2);
8154
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008155 if (!isa<ConstantInt>(IdxOp))
8156 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008157 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008158
8159 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8160 // Okay, we can handle this if the vector we are insertinting into is
8161 // transitively ok.
8162 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8163 // If so, update the mask to reflect the inserted undef.
8164 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8165 return true;
8166 }
8167 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8168 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008169 EI->getOperand(0)->getType() == V->getType()) {
8170 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008171 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008172
8173 // This must be extracting from either LHS or RHS.
8174 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8175 // Okay, we can handle this if the vector we are insertinting into is
8176 // transitively ok.
8177 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8178 // If so, update the mask to reflect the inserted value.
8179 if (EI->getOperand(0) == LHS) {
8180 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008181 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008182 } else {
8183 assert(EI->getOperand(0) == RHS);
8184 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008185 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008186
8187 }
8188 return true;
8189 }
8190 }
8191 }
8192 }
8193 }
8194 // TODO: Handle shufflevector here!
8195
8196 return false;
8197}
8198
8199/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8200/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8201/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008202static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008203 Value *&RHS) {
8204 assert(isa<PackedType>(V->getType()) &&
8205 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008206 "Invalid shuffle!");
8207 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8208
8209 if (isa<UndefValue>(V)) {
8210 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8211 return V;
8212 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008213 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008214 return V;
8215 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8216 // If this is an insert of an extract from some other vector, include it.
8217 Value *VecOp = IEI->getOperand(0);
8218 Value *ScalarOp = IEI->getOperand(1);
8219 Value *IdxOp = IEI->getOperand(2);
8220
8221 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8222 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8223 EI->getOperand(0)->getType() == V->getType()) {
8224 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008225 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8226 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008227
8228 // Either the extracted from or inserted into vector must be RHSVec,
8229 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008230 if (EI->getOperand(0) == RHS || RHS == 0) {
8231 RHS = EI->getOperand(0);
8232 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008233 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008234 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008235 return V;
8236 }
8237
Chris Lattner90951862006-04-16 00:51:47 +00008238 if (VecOp == RHS) {
8239 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008240 // Everything but the extracted element is replaced with the RHS.
8241 for (unsigned i = 0; i != NumElts; ++i) {
8242 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008243 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008244 }
8245 return V;
8246 }
Chris Lattner90951862006-04-16 00:51:47 +00008247
8248 // If this insertelement is a chain that comes from exactly these two
8249 // vectors, return the vector and the effective shuffle.
8250 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8251 return EI->getOperand(0);
8252
Chris Lattner39fac442006-04-15 01:39:45 +00008253 }
8254 }
8255 }
Chris Lattner90951862006-04-16 00:51:47 +00008256 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008257
8258 // Otherwise, can't do anything fancy. Return an identity vector.
8259 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008260 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008261 return V;
8262}
8263
8264Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8265 Value *VecOp = IE.getOperand(0);
8266 Value *ScalarOp = IE.getOperand(1);
8267 Value *IdxOp = IE.getOperand(2);
8268
8269 // If the inserted element was extracted from some other vector, and if the
8270 // indexes are constant, try to turn this into a shufflevector operation.
8271 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8272 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8273 EI->getOperand(0)->getType() == IE.getType()) {
8274 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008275 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8276 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008277
8278 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8279 return ReplaceInstUsesWith(IE, VecOp);
8280
8281 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8282 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8283
8284 // If we are extracting a value from a vector, then inserting it right
8285 // back into the same place, just use the input vector.
8286 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8287 return ReplaceInstUsesWith(IE, VecOp);
8288
8289 // We could theoretically do this for ANY input. However, doing so could
8290 // turn chains of insertelement instructions into a chain of shufflevector
8291 // instructions, and right now we do not merge shufflevectors. As such,
8292 // only do this in a situation where it is clear that there is benefit.
8293 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8294 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8295 // the values of VecOp, except then one read from EIOp0.
8296 // Build a new shuffle mask.
8297 std::vector<Constant*> Mask;
8298 if (isa<UndefValue>(VecOp))
8299 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8300 else {
8301 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008302 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008303 NumVectorElts));
8304 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008305 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008306 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8307 ConstantPacked::get(Mask));
8308 }
8309
8310 // If this insertelement isn't used by some other insertelement, turn it
8311 // (and any insertelements it points to), into one big shuffle.
8312 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8313 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008314 Value *RHS = 0;
8315 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8316 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8317 // We now have a shuffle of LHS, RHS, Mask.
8318 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008319 }
8320 }
8321 }
8322
8323 return 0;
8324}
8325
8326
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008327Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8328 Value *LHS = SVI.getOperand(0);
8329 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008330 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008331
8332 bool MadeChange = false;
8333
Chris Lattner2deeaea2006-10-05 06:55:50 +00008334 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008335 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008336 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8337
Chris Lattner39fac442006-04-15 01:39:45 +00008338 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8339 // the undef, change them to undefs.
8340
Chris Lattner12249be2006-05-25 23:48:38 +00008341 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8342 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8343 if (LHS == RHS || isa<UndefValue>(LHS)) {
8344 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008345 // shuffle(undef,undef,mask) -> undef.
8346 return ReplaceInstUsesWith(SVI, LHS);
8347 }
8348
Chris Lattner12249be2006-05-25 23:48:38 +00008349 // Remap any references to RHS to use LHS.
8350 std::vector<Constant*> Elts;
8351 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008352 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008353 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008354 else {
8355 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8356 (Mask[i] < e && isa<UndefValue>(LHS)))
8357 Mask[i] = 2*e; // Turn into undef.
8358 else
8359 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008360 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008361 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008362 }
Chris Lattner12249be2006-05-25 23:48:38 +00008363 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008364 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008365 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008366 LHS = SVI.getOperand(0);
8367 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008368 MadeChange = true;
8369 }
8370
Chris Lattner0e477162006-05-26 00:29:06 +00008371 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008372 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008373
Chris Lattner12249be2006-05-25 23:48:38 +00008374 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8375 if (Mask[i] >= e*2) continue; // Ignore undef values.
8376 // Is this an identity shuffle of the LHS value?
8377 isLHSID &= (Mask[i] == i);
8378
8379 // Is this an identity shuffle of the RHS value?
8380 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008381 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008382
Chris Lattner12249be2006-05-25 23:48:38 +00008383 // Eliminate identity shuffles.
8384 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8385 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008386
Chris Lattner0e477162006-05-26 00:29:06 +00008387 // If the LHS is a shufflevector itself, see if we can combine it with this
8388 // one without producing an unusual shuffle. Here we are really conservative:
8389 // we are absolutely afraid of producing a shuffle mask not in the input
8390 // program, because the code gen may not be smart enough to turn a merged
8391 // shuffle into two specific shuffles: it may produce worse code. As such,
8392 // we only merge two shuffles if the result is one of the two input shuffle
8393 // masks. In this case, merging the shuffles just removes one instruction,
8394 // which we know is safe. This is good for things like turning:
8395 // (splat(splat)) -> splat.
8396 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8397 if (isa<UndefValue>(RHS)) {
8398 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8399
8400 std::vector<unsigned> NewMask;
8401 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8402 if (Mask[i] >= 2*e)
8403 NewMask.push_back(2*e);
8404 else
8405 NewMask.push_back(LHSMask[Mask[i]]);
8406
8407 // If the result mask is equal to the src shuffle or this shuffle mask, do
8408 // the replacement.
8409 if (NewMask == LHSMask || NewMask == Mask) {
8410 std::vector<Constant*> Elts;
8411 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8412 if (NewMask[i] >= e*2) {
8413 Elts.push_back(UndefValue::get(Type::UIntTy));
8414 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008415 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008416 }
8417 }
8418 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8419 LHSSVI->getOperand(1),
8420 ConstantPacked::get(Elts));
8421 }
8422 }
8423 }
8424
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008425 return MadeChange ? &SVI : 0;
8426}
8427
8428
Robert Bocchinoa8352962006-01-13 22:48:06 +00008429
Chris Lattner99f48c62002-09-02 04:59:56 +00008430void InstCombiner::removeFromWorkList(Instruction *I) {
8431 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8432 WorkList.end());
8433}
8434
Chris Lattner39c98bb2004-12-08 23:43:58 +00008435
8436/// TryToSinkInstruction - Try to move the specified instruction from its
8437/// current block into the beginning of DestBlock, which can only happen if it's
8438/// safe to move the instruction past all of the instructions between it and the
8439/// end of its block.
8440static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8441 assert(I->hasOneUse() && "Invariants didn't hold!");
8442
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008443 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8444 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008445
Chris Lattner39c98bb2004-12-08 23:43:58 +00008446 // Do not sink alloca instructions out of the entry block.
8447 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8448 return false;
8449
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008450 // We can only sink load instructions if there is nothing between the load and
8451 // the end of block that could change the value.
8452 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008453 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8454 Scan != E; ++Scan)
8455 if (Scan->mayWriteToMemory())
8456 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008457 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008458
8459 BasicBlock::iterator InsertPos = DestBlock->begin();
8460 while (isa<PHINode>(InsertPos)) ++InsertPos;
8461
Chris Lattner9f269e42005-08-08 19:11:57 +00008462 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008463 ++NumSunkInst;
8464 return true;
8465}
8466
Chris Lattner1443bc52006-05-11 17:11:52 +00008467/// OptimizeConstantExpr - Given a constant expression and target data layout
8468/// information, symbolically evaluation the constant expr to something simpler
8469/// if possible.
8470static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8471 if (!TD) return CE;
8472
8473 Constant *Ptr = CE->getOperand(0);
8474 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8475 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8476 // If this is a constant expr gep that is effectively computing an
8477 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8478 bool isFoldableGEP = true;
8479 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8480 if (!isa<ConstantInt>(CE->getOperand(i)))
8481 isFoldableGEP = false;
8482 if (isFoldableGEP) {
8483 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8484 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008485 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008486 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8487 return ConstantExpr::getCast(C, CE->getType());
8488 }
8489 }
8490
8491 return CE;
8492}
8493
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008494
8495/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8496/// all reachable code to the worklist.
8497///
8498/// This has a couple of tricks to make the code faster and more powerful. In
8499/// particular, we constant fold and DCE instructions as we go, to avoid adding
8500/// them to the worklist (this significantly speeds up instcombine on code where
8501/// many instructions are dead or constant). Additionally, if we find a branch
8502/// whose condition is a known constant, we only visit the reachable successors.
8503///
8504static void AddReachableCodeToWorklist(BasicBlock *BB,
8505 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008506 std::vector<Instruction*> &WorkList,
8507 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008508 // We have now visited this block! If we've already been here, bail out.
8509 if (!Visited.insert(BB).second) return;
8510
8511 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8512 Instruction *Inst = BBI++;
8513
8514 // DCE instruction if trivially dead.
8515 if (isInstructionTriviallyDead(Inst)) {
8516 ++NumDeadInst;
8517 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8518 Inst->eraseFromParent();
8519 continue;
8520 }
8521
8522 // ConstantProp instruction if trivially constant.
8523 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008524 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8525 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008526 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8527 Inst->replaceAllUsesWith(C);
8528 ++NumConstProp;
8529 Inst->eraseFromParent();
8530 continue;
8531 }
8532
8533 WorkList.push_back(Inst);
8534 }
8535
8536 // Recursively visit successors. If this is a branch or switch on a constant,
8537 // only visit the reachable successor.
8538 TerminatorInst *TI = BB->getTerminator();
8539 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8540 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8541 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008542 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8543 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008544 return;
8545 }
8546 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8547 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8548 // See if this is an explicit destination.
8549 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8550 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008551 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008552 return;
8553 }
8554
8555 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008556 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008557 return;
8558 }
8559 }
8560
8561 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008562 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008563}
8564
Chris Lattner113f4f42002-06-25 16:13:24 +00008565bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008566 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008567 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008568
Chris Lattner4ed40f72005-07-07 20:40:38 +00008569 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008570 // Do a depth-first traversal of the function, populate the worklist with
8571 // the reachable instructions. Ignore blocks that are not reachable. Keep
8572 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008573 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008574 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008575
Chris Lattner4ed40f72005-07-07 20:40:38 +00008576 // Do a quick scan over the function. If we find any blocks that are
8577 // unreachable, remove any instructions inside of them. This prevents
8578 // the instcombine code from having to deal with some bad special cases.
8579 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8580 if (!Visited.count(BB)) {
8581 Instruction *Term = BB->getTerminator();
8582 while (Term != BB->begin()) { // Remove instrs bottom-up
8583 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008584
Chris Lattner4ed40f72005-07-07 20:40:38 +00008585 DEBUG(std::cerr << "IC: DCE: " << *I);
8586 ++NumDeadInst;
8587
8588 if (!I->use_empty())
8589 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8590 I->eraseFromParent();
8591 }
8592 }
8593 }
Chris Lattnerca081252001-12-14 16:52:21 +00008594
8595 while (!WorkList.empty()) {
8596 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8597 WorkList.pop_back();
8598
Chris Lattner1443bc52006-05-11 17:11:52 +00008599 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008600 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008601 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008602 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008603 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008604 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008605
Chris Lattnercd517ff2005-01-28 19:32:01 +00008606 DEBUG(std::cerr << "IC: DCE: " << *I);
8607
8608 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008609 removeFromWorkList(I);
8610 continue;
8611 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008612
Chris Lattner1443bc52006-05-11 17:11:52 +00008613 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008614 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008615 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8616 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008617 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8618
Chris Lattner1443bc52006-05-11 17:11:52 +00008619 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008620 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008621 ReplaceInstUsesWith(*I, C);
8622
Chris Lattner99f48c62002-09-02 04:59:56 +00008623 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008624 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008625 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008626 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008627 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008628
Chris Lattner39c98bb2004-12-08 23:43:58 +00008629 // See if we can trivially sink this instruction to a successor basic block.
8630 if (I->hasOneUse()) {
8631 BasicBlock *BB = I->getParent();
8632 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8633 if (UserParent != BB) {
8634 bool UserIsSuccessor = false;
8635 // See if the user is one of our successors.
8636 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8637 if (*SI == UserParent) {
8638 UserIsSuccessor = true;
8639 break;
8640 }
8641
8642 // If the user is one of our immediate successors, and if that successor
8643 // only has us as a predecessors (we'd have to split the critical edge
8644 // otherwise), we can keep going.
8645 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8646 next(pred_begin(UserParent)) == pred_end(UserParent))
8647 // Okay, the CFG is simple enough, try to sink this instruction.
8648 Changed |= TryToSinkInstruction(I, UserParent);
8649 }
8650 }
8651
Chris Lattnerca081252001-12-14 16:52:21 +00008652 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008653 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008654 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008655 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008656 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008657 DEBUG(std::cerr << "IC: Old = " << *I
8658 << " New = " << *Result);
8659
Chris Lattner396dbfe2004-06-09 05:08:07 +00008660 // Everything uses the new instruction now.
8661 I->replaceAllUsesWith(Result);
8662
8663 // Push the new instruction and any users onto the worklist.
8664 WorkList.push_back(Result);
8665 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008666
8667 // Move the name to the new instruction first...
8668 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008669 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008670
8671 // Insert the new instruction into the basic block...
8672 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008673 BasicBlock::iterator InsertPos = I;
8674
8675 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8676 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8677 ++InsertPos;
8678
8679 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008680
Chris Lattner63d75af2004-05-01 23:27:23 +00008681 // Make sure that we reprocess all operands now that we reduced their
8682 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008683 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8684 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8685 WorkList.push_back(OpI);
8686
Chris Lattner396dbfe2004-06-09 05:08:07 +00008687 // Instructions can end up on the worklist more than once. Make sure
8688 // we do not process an instruction that has been deleted.
8689 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008690
8691 // Erase the old instruction.
8692 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008693 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008694 DEBUG(std::cerr << "IC: MOD = " << *I);
8695
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008696 // If the instruction was modified, it's possible that it is now dead.
8697 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008698 if (isInstructionTriviallyDead(I)) {
8699 // Make sure we process all operands now that we are reducing their
8700 // use counts.
8701 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8702 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8703 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008704
Chris Lattner63d75af2004-05-01 23:27:23 +00008705 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008706 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008707 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008708 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008709 } else {
8710 WorkList.push_back(Result);
8711 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008712 }
Chris Lattner053c0932002-05-14 15:24:07 +00008713 }
Chris Lattner260ab202002-04-18 17:39:14 +00008714 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008715 }
8716 }
8717
Chris Lattner260ab202002-04-18 17:39:14 +00008718 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008719}
8720
Brian Gaeke38b79e82004-07-27 17:43:21 +00008721FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008722 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008723}
Brian Gaeke960707c2003-11-11 22:41:34 +00008724