blob: 797b2b8db2e2b6e4622600a3f3734110da86cffc [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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000054#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000062 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000064
Chris Lattnerc8e66542002-04-27 06:56:12 +000065 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000066 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000069 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000070
Chris Lattner51ea1272004-02-28 05:22:00 +000071 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
73 /// now.
74 ///
Chris Lattner2590e512006-02-07 06:56:34 +000075 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000076 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000077 UI != UE; ++UI)
78 WorkList.push_back(cast<Instruction>(*UI));
79 }
80
Chris Lattner51ea1272004-02-28 05:22:00 +000081 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
83 ///
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
88 }
89
Chris Lattner99f48c62002-09-02 04:59:56 +000090 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000092 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000093 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000094
Chris Lattnerf12cc842002-04-28 21:27:06 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000096 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000097 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000098 }
99
Chris Lattner69193f92004-04-05 01:30:19 +0000100 TargetData &getTargetData() const { return *TD; }
101
Chris Lattner260ab202002-04-18 17:39:14 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000106 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000107 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000108 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
Chris Lattner0798af32005-01-13 20:14:25 +0000120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000122 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000125 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000128 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000133 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000134 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000135 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000136 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000137 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000138 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000139 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000142
143 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145
Chris Lattner970c33a2003-06-19 17:00:31 +0000146 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000147 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000148 bool transformConstExprCastCall(CallSite CS);
149
Chris Lattner69193f92004-04-05 01:30:19 +0000150 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
153 //
Chris Lattner623826c2004-09-28 21:48:02 +0000154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000160 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000161 }
162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
165 /// cast.
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000168
Chris Lattnere79d2492006-04-06 19:19:17 +0000169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
171
Chris Lattner7e794272004-09-24 15:21:34 +0000172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
174 return C;
175 }
176
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
181 // modified.
182 //
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000184 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000185 if (&I != V) {
186 I.replaceAllUsesWith(V);
187 return &I;
188 } else {
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000192 return &I;
193 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000195
Chris Lattner2590e512006-02-07 06:56:34 +0000196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
201 //
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
204 if (Old != New)
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000210 return true;
211 }
212
Chris Lattner51ea1272004-02-28 05:22:00 +0000213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
216 // this function.
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000221 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000222 return 0; // Don't do anything with FI
223 }
224
Chris Lattner3ac7c262003-08-13 20:16:26 +0000225 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
229 ///
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
232
Chris Lattner7fb29e12003-03-11 00:12:48 +0000233 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000234 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000235 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000236
Chris Lattner0157e7f2006-02-11 09:31:47 +0000237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
239 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000240
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
245
Chris Lattner7515cab2004-11-14 19:13:23 +0000246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
250
Chris Lattnerba1cb382003-09-19 17:17:26 +0000251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000253
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000259 Instruction *MatchBSwap(BinaryOperator &I);
260
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000261 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000262 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000263
Chris Lattnerc8b70922002-07-26 21:12:46 +0000264 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000265}
266
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000268// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000269static unsigned getComplexity(Value *V) {
270 if (isa<Instruction>(V)) {
271 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000272 return 3;
273 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000274 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000275 if (isa<Argument>(V)) return 3;
276 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277}
Chris Lattner260ab202002-04-18 17:39:14 +0000278
Chris Lattner7fb29e12003-03-11 00:12:48 +0000279// isOnlyUse - Return true if this instruction will be deleted if we stop using
280// it.
281static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000282 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000283}
284
Chris Lattnere79e8542004-02-23 06:38:22 +0000285// getPromotedType - Return the specified type promoted as it would be to pass
286// though a va_arg area...
287static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000288 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000289 case Type::SByteTyID:
290 case Type::ShortTyID: return Type::IntTy;
291 case Type::UByteTyID:
292 case Type::UShortTyID: return Type::UIntTy;
293 case Type::FloatTyID: return Type::DoubleTy;
294 default: return Ty;
295 }
296}
297
Chris Lattner567b81f2005-09-13 00:40:14 +0000298/// isCast - If the specified operand is a CastInst or a constant expr cast,
299/// return the operand value, otherwise return null.
300static Value *isCast(Value *V) {
301 if (CastInst *I = dyn_cast<CastInst>(V))
302 return I->getOperand(0);
303 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
304 if (CE->getOpcode() == Instruction::Cast)
305 return CE->getOperand(0);
306 return 0;
307}
308
Chris Lattner1d441ad2006-05-06 09:00:16 +0000309enum CastType {
310 Noop = 0,
311 Truncate = 1,
312 Signext = 2,
313 Zeroext = 3
314};
315
316/// getCastType - In the future, we will split the cast instruction into these
317/// various types. Until then, we have to do the analysis here.
318static CastType getCastType(const Type *Src, const Type *Dest) {
319 assert(Src->isIntegral() && Dest->isIntegral() &&
320 "Only works on integral types!");
321 unsigned SrcSize = Src->getPrimitiveSizeInBits();
322 unsigned DestSize = Dest->getPrimitiveSizeInBits();
323
324 if (SrcSize == DestSize) return Noop;
325 if (SrcSize > DestSize) return Truncate;
326 if (Src->isSigned()) return Signext;
327 return Zeroext;
328}
329
330
331// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
332// instruction.
333//
334static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
335 const Type *DstTy, TargetData *TD) {
336
337 // It is legal to eliminate the instruction if casting A->B->A if the sizes
338 // are identical and the bits don't get reinterpreted (for example
339 // int->float->int would not be allowed).
340 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
341 return true;
342
343 // If we are casting between pointer and integer types, treat pointers as
344 // integers of the appropriate size for the code below.
345 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
346 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
347 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
348
349 // Allow free casting and conversion of sizes as long as the sign doesn't
350 // change...
351 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
352 CastType FirstCast = getCastType(SrcTy, MidTy);
353 CastType SecondCast = getCastType(MidTy, DstTy);
354
355 // Capture the effect of these two casts. If the result is a legal cast,
356 // the CastType is stored here, otherwise a special code is used.
357 static const unsigned CastResult[] = {
358 // First cast is noop
359 0, 1, 2, 3,
360 // First cast is a truncate
361 1, 1, 4, 4, // trunc->extend is not safe to eliminate
362 // First cast is a sign ext
363 2, 5, 2, 4, // signext->zeroext never ok
364 // First cast is a zero ext
365 3, 5, 3, 3,
366 };
367
368 unsigned Result = CastResult[FirstCast*4+SecondCast];
369 switch (Result) {
370 default: assert(0 && "Illegal table value!");
371 case 0:
372 case 1:
373 case 2:
374 case 3:
375 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
376 // truncates, we could eliminate more casts.
377 return (unsigned)getCastType(SrcTy, DstTy) == Result;
378 case 4:
379 return false; // Not possible to eliminate this here.
380 case 5:
381 // Sign or zero extend followed by truncate is always ok if the result
382 // is a truncate or noop.
383 CastType ResultCast = getCastType(SrcTy, DstTy);
384 if (ResultCast == Noop || ResultCast == Truncate)
385 return true;
386 // Otherwise we are still growing the value, we are only safe if the
387 // result will match the sign/zeroextendness of the result.
388 return ResultCast == FirstCast;
389 }
390 }
391
392 // If this is a cast from 'float -> double -> integer', cast from
393 // 'float -> integer' directly, as the value isn't changed by the
394 // float->double conversion.
395 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
396 DstTy->isIntegral() &&
397 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
398 return true;
399
400 // Packed type conversions don't modify bits.
401 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
402 return true;
403
404 return false;
405}
406
407/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
408/// in any code being generated. It does not require codegen if V is simple
409/// enough or if the cast can be folded into other casts.
410static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
411 if (V->getType() == Ty || isa<Constant>(V)) return false;
412
413 // If this is a noop cast, it isn't real codegen.
414 if (V->getType()->isLosslesslyConvertibleTo(Ty))
415 return false;
416
Chris Lattner99155be2006-05-25 23:24:33 +0000417 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000418 if (const CastInst *CI = dyn_cast<CastInst>(V))
419 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
420 TD))
421 return false;
422 return true;
423}
424
425/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
426/// InsertBefore instruction. This is specialized a bit to avoid inserting
427/// casts that are known to not do anything...
428///
429Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
430 Instruction *InsertBefore) {
431 if (V->getType() == DestTy) return V;
432 if (Constant *C = dyn_cast<Constant>(V))
433 return ConstantExpr::getCast(C, DestTy);
434
435 CastInst *CI = new CastInst(V, DestTy, V->getName());
436 InsertNewInstBefore(CI, *InsertBefore);
437 return CI;
438}
439
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000440// SimplifyCommutative - This performs a few simplifications for commutative
441// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000442//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000443// 1. Order operands such that they are listed from right (least complex) to
444// left (most complex). This puts constants before unary operators before
445// binary operators.
446//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000447// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
448// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000449//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000451 bool Changed = false;
452 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
453 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000454
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 if (!I.isAssociative()) return Changed;
456 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000457 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
458 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
459 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000460 Constant *Folded = ConstantExpr::get(I.getOpcode(),
461 cast<Constant>(I.getOperand(1)),
462 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000463 I.setOperand(0, Op->getOperand(0));
464 I.setOperand(1, Folded);
465 return true;
466 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
467 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
468 isOnlyUse(Op) && isOnlyUse(Op1)) {
469 Constant *C1 = cast<Constant>(Op->getOperand(1));
470 Constant *C2 = cast<Constant>(Op1->getOperand(1));
471
472 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000473 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000474 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
475 Op1->getOperand(0),
476 Op1->getName(), &I);
477 WorkList.push_back(New);
478 I.setOperand(0, New);
479 I.setOperand(1, Folded);
480 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000481 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000483 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000484}
Chris Lattnerca081252001-12-14 16:52:21 +0000485
Chris Lattnerbb74e222003-03-10 23:06:50 +0000486// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
487// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000488//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489static inline Value *dyn_castNegVal(Value *V) {
490 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000491 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000492
Chris Lattner9ad0d552004-12-14 20:08:06 +0000493 // Constants can be considered to be negated values if they can be folded.
494 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
495 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000496 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000497}
498
Chris Lattnerbb74e222003-03-10 23:06:50 +0000499static inline Value *dyn_castNotVal(Value *V) {
500 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000501 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000502
503 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000504 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000505 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000506 return 0;
507}
508
Chris Lattner7fb29e12003-03-11 00:12:48 +0000509// dyn_castFoldableMul - If this value is a multiply that can be folded into
510// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000511// non-constant operand of the multiply, and set CST to point to the multiplier.
512// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000513//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000514static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000515 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000516 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000517 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000518 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000519 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000520 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000522 // The multiplier is really 1 << CST.
523 Constant *One = ConstantInt::get(V->getType(), 1);
524 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
525 return I->getOperand(0);
526 }
527 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000528 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000529}
Chris Lattner31ae8632002-08-14 17:51:49 +0000530
Chris Lattner0798af32005-01-13 20:14:25 +0000531/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
532/// expression, return it.
533static User *dyn_castGetElementPtr(Value *V) {
534 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
535 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
536 if (CE->getOpcode() == Instruction::GetElementPtr)
537 return cast<User>(V);
538 return false;
539}
540
Chris Lattner623826c2004-09-28 21:48:02 +0000541// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000542static ConstantInt *AddOne(ConstantInt *C) {
543 return cast<ConstantInt>(ConstantExpr::getAdd(C,
544 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000545}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000546static ConstantInt *SubOne(ConstantInt *C) {
547 return cast<ConstantInt>(ConstantExpr::getSub(C,
548 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000549}
550
Chris Lattner0157e7f2006-02-11 09:31:47 +0000551/// GetConstantInType - Return a ConstantInt with the specified type and value.
552///
Chris Lattneree0f2802006-02-12 02:07:56 +0000553static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000554 if (Ty->isUnsigned())
555 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000556 else if (Ty->getTypeID() == Type::BoolTyID)
557 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000558 int64_t SVal = Val;
559 SVal <<= 64-Ty->getPrimitiveSizeInBits();
560 SVal >>= 64-Ty->getPrimitiveSizeInBits();
561 return ConstantSInt::get(Ty, SVal);
562}
563
564
Chris Lattner4534dd592006-02-09 07:38:58 +0000565/// ComputeMaskedBits - Determine which of the bits specified in Mask are
566/// known to be either zero or one and return them in the KnownZero/KnownOne
567/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
568/// processing.
569static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
570 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000571 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
572 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000573 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000574 // optimized based on the contradictory assumption that it is non-zero.
575 // Because instcombine aggressively folds operations with undef args anyway,
576 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000577 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
578 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000579 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000580 KnownZero = ~KnownOne & Mask;
581 return;
582 }
583
584 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000585 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000586 return; // Limit search depth.
587
588 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000589 Instruction *I = dyn_cast<Instruction>(V);
590 if (!I) return;
591
Chris Lattnerfb296922006-05-04 17:33:35 +0000592 Mask &= V->getType()->getIntegralTypeMask();
593
Chris Lattner0157e7f2006-02-11 09:31:47 +0000594 switch (I->getOpcode()) {
595 case Instruction::And:
596 // If either the LHS or the RHS are Zero, the result is zero.
597 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
598 Mask &= ~KnownZero;
599 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
600 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
601 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
602
603 // Output known-1 bits are only known if set in both the LHS & RHS.
604 KnownOne &= KnownOne2;
605 // Output known-0 are known to be clear if zero in either the LHS | RHS.
606 KnownZero |= KnownZero2;
607 return;
608 case Instruction::Or:
609 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
610 Mask &= ~KnownOne;
611 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
612 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
613 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
614
615 // Output known-0 bits are only known if clear in both the LHS & RHS.
616 KnownZero &= KnownZero2;
617 // Output known-1 are known to be set if set in either the LHS | RHS.
618 KnownOne |= KnownOne2;
619 return;
620 case Instruction::Xor: {
621 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
622 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
623 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
624 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
625
626 // Output known-0 bits are known if clear or set in both the LHS & RHS.
627 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
628 // Output known-1 are known to be set if set in only one of the LHS, RHS.
629 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
630 KnownZero = KnownZeroOut;
631 return;
632 }
633 case Instruction::Select:
634 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
635 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
636 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
637 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
638
639 // Only known if known in both the LHS and RHS.
640 KnownOne &= KnownOne2;
641 KnownZero &= KnownZero2;
642 return;
643 case Instruction::Cast: {
644 const Type *SrcTy = I->getOperand(0)->getType();
645 if (!SrcTy->isIntegral()) return;
646
647 // If this is an integer truncate or noop, just look in the input.
648 if (SrcTy->getPrimitiveSizeInBits() >=
649 I->getType()->getPrimitiveSizeInBits()) {
650 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000651 return;
652 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000653
Chris Lattner0157e7f2006-02-11 09:31:47 +0000654 // Sign or Zero extension. Compute the bits in the result that are not
655 // present in the input.
656 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
657 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000658
Chris Lattner0157e7f2006-02-11 09:31:47 +0000659 // Handle zero extension.
660 if (!SrcTy->isSigned()) {
661 Mask &= SrcTy->getIntegralTypeMask();
662 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 // The top bits are known to be zero.
665 KnownZero |= NewBits;
666 } else {
667 // Sign extension.
668 Mask &= SrcTy->getIntegralTypeMask();
669 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
670 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000671
Chris Lattner0157e7f2006-02-11 09:31:47 +0000672 // If the sign bit of the input is known set or clear, then we know the
673 // top bits of the result.
674 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
675 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000676 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000677 KnownOne &= ~NewBits;
678 } else if (KnownOne & InSignBit) { // Input sign bit known set
679 KnownOne |= NewBits;
680 KnownZero &= ~NewBits;
681 } else { // Input sign bit unknown
682 KnownZero &= ~NewBits;
683 KnownOne &= ~NewBits;
684 }
685 }
686 return;
687 }
688 case Instruction::Shl:
689 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
690 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
691 Mask >>= SA->getValue();
692 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
693 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
694 KnownZero <<= SA->getValue();
695 KnownOne <<= SA->getValue();
696 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
697 return;
698 }
699 break;
700 case Instruction::Shr:
701 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
702 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
703 // Compute the new bits that are at the top now.
704 uint64_t HighBits = (1ULL << SA->getValue())-1;
705 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
706
707 if (I->getType()->isUnsigned()) { // Unsigned shift right.
708 Mask <<= SA->getValue();
709 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
710 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
711 KnownZero >>= SA->getValue();
712 KnownOne >>= SA->getValue();
713 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000714 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000715 Mask <<= SA->getValue();
716 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
717 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
718 KnownZero >>= SA->getValue();
719 KnownOne >>= SA->getValue();
720
721 // Handle the sign bits.
722 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
723 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
724
725 if (KnownZero & SignBit) { // New bits are known zero.
726 KnownZero |= HighBits;
727 } else if (KnownOne & SignBit) { // New bits are known one.
728 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000729 }
730 }
731 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000732 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000733 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000734 }
Chris Lattner92a68652006-02-07 08:05:22 +0000735}
736
737/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
738/// this predicate to simplify operations downstream. Mask is known to be zero
739/// for bits that V cannot have.
740static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000741 uint64_t KnownZero, KnownOne;
742 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
744 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000745}
746
Chris Lattner0157e7f2006-02-11 09:31:47 +0000747/// ShrinkDemandedConstant - Check to see if the specified operand of the
748/// specified instruction is a constant integer. If so, check to see if there
749/// are any bits set in the constant that are not demanded. If so, shrink the
750/// constant and return true.
751static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
752 uint64_t Demanded) {
753 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
754 if (!OpC) return false;
755
756 // If there are no bits set that aren't demanded, nothing to do.
757 if ((~Demanded & OpC->getZExtValue()) == 0)
758 return false;
759
760 // This is producing any bits that are not needed, shrink the RHS.
761 uint64_t Val = Demanded & OpC->getZExtValue();
762 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
763 return true;
764}
765
Chris Lattneree0f2802006-02-12 02:07:56 +0000766// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
767// set of known zero and one bits, compute the maximum and minimum values that
768// could have the specified known zero and known one bits, returning them in
769// min/max.
770static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
771 uint64_t KnownZero,
772 uint64_t KnownOne,
773 int64_t &Min, int64_t &Max) {
774 uint64_t TypeBits = Ty->getIntegralTypeMask();
775 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
776
777 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
778
779 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
780 // bit if it is unknown.
781 Min = KnownOne;
782 Max = KnownOne|UnknownBits;
783
784 if (SignBit & UnknownBits) { // Sign bit is unknown
785 Min |= SignBit;
786 Max &= ~SignBit;
787 }
788
789 // Sign extend the min/max values.
790 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
791 Min = (Min << ShAmt) >> ShAmt;
792 Max = (Max << ShAmt) >> ShAmt;
793}
794
795// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
796// a set of known zero and one bits, compute the maximum and minimum values that
797// could have the specified known zero and known one bits, returning them in
798// min/max.
799static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
800 uint64_t KnownZero,
801 uint64_t KnownOne,
802 uint64_t &Min,
803 uint64_t &Max) {
804 uint64_t TypeBits = Ty->getIntegralTypeMask();
805 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806
807 // The minimum value is when the unknown bits are all zeros.
808 Min = KnownOne;
809 // The maximum value is when the unknown bits are all ones.
810 Max = KnownOne|UnknownBits;
811}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000812
813
814/// SimplifyDemandedBits - Look at V. At this point, we know that only the
815/// DemandedMask bits of the result of V are ever used downstream. If we can
816/// use this information to simplify V, do so and return true. Otherwise,
817/// analyze the expression and return a mask of KnownOne and KnownZero bits for
818/// the expression (used to simplify the caller). The KnownZero/One bits may
819/// only be accurate for those bits in the DemandedMask.
820bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
821 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000822 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000823 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
824 // We know all of the bits for a constant!
825 KnownOne = CI->getZExtValue() & DemandedMask;
826 KnownZero = ~KnownOne & DemandedMask;
827 return false;
828 }
829
830 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000831 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000832 if (Depth != 0) { // Not at the root.
833 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
834 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000835 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000836 }
Chris Lattner2590e512006-02-07 06:56:34 +0000837 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000838 // just set the DemandedMask to all bits.
839 DemandedMask = V->getType()->getIntegralTypeMask();
840 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000841 if (V != UndefValue::get(V->getType()))
842 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
843 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000844 } else if (Depth == 6) { // Limit search depth.
845 return false;
846 }
847
848 Instruction *I = dyn_cast<Instruction>(V);
849 if (!I) return false; // Only analyze instructions.
850
Chris Lattnerfb296922006-05-04 17:33:35 +0000851 DemandedMask &= V->getType()->getIntegralTypeMask();
852
Chris Lattner0157e7f2006-02-11 09:31:47 +0000853 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000854 switch (I->getOpcode()) {
855 default: break;
856 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857 // If either the LHS or the RHS are Zero, the result is zero.
858 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
859 KnownZero, KnownOne, Depth+1))
860 return true;
861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
862
863 // If something is known zero on the RHS, the bits aren't demanded on the
864 // LHS.
865 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
866 KnownZero2, KnownOne2, Depth+1))
867 return true;
868 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
869
870 // If all of the demanded bits are known one on one side, return the other.
871 // These bits cannot contribute to the result of the 'and'.
872 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
873 return UpdateValueUsesWith(I, I->getOperand(0));
874 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
875 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000876
877 // If all of the demanded bits in the inputs are known zeros, return zero.
878 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
879 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
880
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000882 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883 return UpdateValueUsesWith(I, I);
884
885 // Output known-1 bits are only known if set in both the LHS & RHS.
886 KnownOne &= KnownOne2;
887 // Output known-0 are known to be clear if zero in either the LHS | RHS.
888 KnownZero |= KnownZero2;
889 break;
890 case Instruction::Or:
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 KnownZero, KnownOne, Depth+1))
893 return true;
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
896 KnownZero2, KnownOne2, Depth+1))
897 return true;
898 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
899
900 // If all of the demanded bits are known zero on one side, return the other.
901 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000902 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000903 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000904 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000905 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000906
907 // If all of the potentially set bits on one side are known to be set on
908 // the other side, just use the 'other' side.
909 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
910 (DemandedMask & (~KnownZero)))
911 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000912 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
913 (DemandedMask & (~KnownZero2)))
914 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000915
916 // If the RHS is a constant, see if we can simplify it.
917 if (ShrinkDemandedConstant(I, 1, DemandedMask))
918 return UpdateValueUsesWith(I, I);
919
920 // Output known-0 bits are only known if clear in both the LHS & RHS.
921 KnownZero &= KnownZero2;
922 // Output known-1 are known to be set if set in either the LHS | RHS.
923 KnownOne |= KnownOne2;
924 break;
925 case Instruction::Xor: {
926 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
927 KnownZero, KnownOne, Depth+1))
928 return true;
929 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
930 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
931 KnownZero2, KnownOne2, Depth+1))
932 return true;
933 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
934
935 // If all of the demanded bits are known zero on one side, return the other.
936 // These bits cannot contribute to the result of the 'xor'.
937 if ((DemandedMask & KnownZero) == DemandedMask)
938 return UpdateValueUsesWith(I, I->getOperand(0));
939 if ((DemandedMask & KnownZero2) == DemandedMask)
940 return UpdateValueUsesWith(I, I->getOperand(1));
941
942 // Output known-0 bits are known if clear or set in both the LHS & RHS.
943 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
944 // Output known-1 are known to be set if set in only one of the LHS, RHS.
945 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
946
947 // If all of the unknown bits are known to be zero on one side or the other
948 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000949 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000950 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
951 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
952 Instruction *Or =
953 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
954 I->getName());
955 InsertNewInstBefore(Or, *I);
956 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000957 }
958 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000959
Chris Lattner5b2edb12006-02-12 08:02:11 +0000960 // If all of the demanded bits on one side are known, and all of the set
961 // bits on that side are also known to be set on the other side, turn this
962 // into an AND, as we know the bits will be cleared.
963 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
964 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
965 if ((KnownOne & KnownOne2) == KnownOne) {
966 Constant *AndC = GetConstantInType(I->getType(),
967 ~KnownOne & DemandedMask);
968 Instruction *And =
969 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
970 InsertNewInstBefore(And, *I);
971 return UpdateValueUsesWith(I, And);
972 }
973 }
974
Chris Lattner0157e7f2006-02-11 09:31:47 +0000975 // If the RHS is a constant, see if we can simplify it.
976 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
977 if (ShrinkDemandedConstant(I, 1, DemandedMask))
978 return UpdateValueUsesWith(I, I);
979
980 KnownZero = KnownZeroOut;
981 KnownOne = KnownOneOut;
982 break;
983 }
984 case Instruction::Select:
985 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
986 KnownZero, KnownOne, Depth+1))
987 return true;
988 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
989 KnownZero2, KnownOne2, Depth+1))
990 return true;
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
992 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
993
994 // If the operands are constants, see if we can simplify them.
995 if (ShrinkDemandedConstant(I, 1, DemandedMask))
996 return UpdateValueUsesWith(I, I);
997 if (ShrinkDemandedConstant(I, 2, DemandedMask))
998 return UpdateValueUsesWith(I, I);
999
1000 // Only known if known in both the LHS and RHS.
1001 KnownOne &= KnownOne2;
1002 KnownZero &= KnownZero2;
1003 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001004 case Instruction::Cast: {
1005 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001006 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001007
Chris Lattner0157e7f2006-02-11 09:31:47 +00001008 // If this is an integer truncate or noop, just look in the input.
1009 if (SrcTy->getPrimitiveSizeInBits() >=
1010 I->getType()->getPrimitiveSizeInBits()) {
1011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1013 return true;
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1015 break;
1016 }
1017
1018 // Sign or Zero extension. Compute the bits in the result that are not
1019 // present in the input.
1020 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1021 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1022
1023 // Handle zero extension.
1024 if (!SrcTy->isSigned()) {
1025 DemandedMask &= SrcTy->getIntegralTypeMask();
1026 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1027 KnownZero, KnownOne, Depth+1))
1028 return true;
1029 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1030 // The top bits are known to be zero.
1031 KnownZero |= NewBits;
1032 } else {
1033 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1036
1037 // If any of the sign extended bits are demanded, we know that the sign
1038 // bit is demanded.
1039 if (NewBits & DemandedMask)
1040 InputDemandedBits |= InSignBit;
1041
1042 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001043 KnownZero, KnownOne, Depth+1))
1044 return true;
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1046
1047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001049
Chris Lattner0157e7f2006-02-11 09:31:47 +00001050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
1052 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001053 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001054 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001055 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001056 I->getOperand(0)->getName());
1057 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001058 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001059 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1060 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001061 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001062 } else if (KnownOne & InSignBit) { // Input sign bit known set
1063 KnownOne |= NewBits;
1064 KnownZero &= ~NewBits;
1065 } else { // Input sign bit unknown
1066 KnownZero &= ~NewBits;
1067 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001068 }
Chris Lattner2590e512006-02-07 06:56:34 +00001069 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001070 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001071 }
Chris Lattner2590e512006-02-07 06:56:34 +00001072 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001073 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1074 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1075 KnownZero, KnownOne, Depth+1))
1076 return true;
1077 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1078 KnownZero <<= SA->getValue();
1079 KnownOne <<= SA->getValue();
1080 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1081 }
Chris Lattner2590e512006-02-07 06:56:34 +00001082 break;
1083 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001084 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1085 unsigned ShAmt = SA->getValue();
1086
1087 // Compute the new bits that are at the top now.
1088 uint64_t HighBits = (1ULL << ShAmt)-1;
1089 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001090 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001091 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001092 if (SimplifyDemandedBits(I->getOperand(0),
1093 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001094 KnownZero, KnownOne, Depth+1))
1095 return true;
1096 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001097 KnownZero &= TypeMask;
1098 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001099 KnownZero >>= ShAmt;
1100 KnownOne >>= ShAmt;
1101 KnownZero |= HighBits; // high bits known zero.
1102 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001103 if (SimplifyDemandedBits(I->getOperand(0),
1104 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001105 KnownZero, KnownOne, Depth+1))
1106 return true;
1107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001108 KnownZero &= TypeMask;
1109 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001110 KnownZero >>= SA->getValue();
1111 KnownOne >>= SA->getValue();
1112
1113 // Handle the sign bits.
1114 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1115 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1116
1117 // If the input sign bit is known to be zero, or if none of the top bits
1118 // are demanded, turn this into an unsigned shift right.
1119 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1120 // Convert the input to unsigned.
1121 Instruction *NewVal;
1122 NewVal = new CastInst(I->getOperand(0),
1123 I->getType()->getUnsignedVersion(),
1124 I->getOperand(0)->getName());
1125 InsertNewInstBefore(NewVal, *I);
1126 // Perform the unsigned shift right.
1127 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1128 InsertNewInstBefore(NewVal, *I);
1129 // Then cast that to the destination type.
1130 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1131 InsertNewInstBefore(NewVal, *I);
1132 return UpdateValueUsesWith(I, NewVal);
1133 } else if (KnownOne & SignBit) { // New bits are known one.
1134 KnownOne |= HighBits;
1135 }
Chris Lattner2590e512006-02-07 06:56:34 +00001136 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001137 }
Chris Lattner2590e512006-02-07 06:56:34 +00001138 break;
1139 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001140
1141 // If the client is only demanding bits that we know, return the known
1142 // constant.
1143 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1144 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001145 return false;
1146}
1147
Chris Lattner623826c2004-09-28 21:48:02 +00001148// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1149// true when both operands are equal...
1150//
1151static bool isTrueWhenEqual(Instruction &I) {
1152 return I.getOpcode() == Instruction::SetEQ ||
1153 I.getOpcode() == Instruction::SetGE ||
1154 I.getOpcode() == Instruction::SetLE;
1155}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001156
1157/// AssociativeOpt - Perform an optimization on an associative operator. This
1158/// function is designed to check a chain of associative operators for a
1159/// potential to apply a certain optimization. Since the optimization may be
1160/// applicable if the expression was reassociated, this checks the chain, then
1161/// reassociates the expression as necessary to expose the optimization
1162/// opportunity. This makes use of a special Functor, which must define
1163/// 'shouldApply' and 'apply' methods.
1164///
1165template<typename Functor>
1166Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1167 unsigned Opcode = Root.getOpcode();
1168 Value *LHS = Root.getOperand(0);
1169
1170 // Quick check, see if the immediate LHS matches...
1171 if (F.shouldApply(LHS))
1172 return F.apply(Root);
1173
1174 // Otherwise, if the LHS is not of the same opcode as the root, return.
1175 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001176 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001177 // Should we apply this transform to the RHS?
1178 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1179
1180 // If not to the RHS, check to see if we should apply to the LHS...
1181 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1182 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1183 ShouldApply = true;
1184 }
1185
1186 // If the functor wants to apply the optimization to the RHS of LHSI,
1187 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1188 if (ShouldApply) {
1189 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001190
Chris Lattnerb8b97502003-08-13 19:01:45 +00001191 // Now all of the instructions are in the current basic block, go ahead
1192 // and perform the reassociation.
1193 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1194
1195 // First move the selected RHS to the LHS of the root...
1196 Root.setOperand(0, LHSI->getOperand(1));
1197
1198 // Make what used to be the LHS of the root be the user of the root...
1199 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001200 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001201 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1202 return 0;
1203 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001204 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001205 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001206 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1207 BasicBlock::iterator ARI = &Root; ++ARI;
1208 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1209 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001210
1211 // Now propagate the ExtraOperand down the chain of instructions until we
1212 // get to LHSI.
1213 while (TmpLHSI != LHSI) {
1214 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001215 // Move the instruction to immediately before the chain we are
1216 // constructing to avoid breaking dominance properties.
1217 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1218 BB->getInstList().insert(ARI, NextLHSI);
1219 ARI = NextLHSI;
1220
Chris Lattnerb8b97502003-08-13 19:01:45 +00001221 Value *NextOp = NextLHSI->getOperand(1);
1222 NextLHSI->setOperand(1, ExtraOperand);
1223 TmpLHSI = NextLHSI;
1224 ExtraOperand = NextOp;
1225 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001226
Chris Lattnerb8b97502003-08-13 19:01:45 +00001227 // Now that the instructions are reassociated, have the functor perform
1228 // the transformation...
1229 return F.apply(Root);
1230 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001231
Chris Lattnerb8b97502003-08-13 19:01:45 +00001232 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1233 }
1234 return 0;
1235}
1236
1237
1238// AddRHS - Implements: X + X --> X << 1
1239struct AddRHS {
1240 Value *RHS;
1241 AddRHS(Value *rhs) : RHS(rhs) {}
1242 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1243 Instruction *apply(BinaryOperator &Add) const {
1244 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1245 ConstantInt::get(Type::UByteTy, 1));
1246 }
1247};
1248
1249// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1250// iff C1&C2 == 0
1251struct AddMaskingAnd {
1252 Constant *C2;
1253 AddMaskingAnd(Constant *c) : C2(c) {}
1254 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001255 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001256 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001257 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001258 }
1259 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001260 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001261 }
1262};
1263
Chris Lattner86102b82005-01-01 16:22:27 +00001264static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001265 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001266 if (isa<CastInst>(I)) {
1267 if (Constant *SOC = dyn_cast<Constant>(SO))
1268 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001269
Chris Lattner86102b82005-01-01 16:22:27 +00001270 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1271 SO->getName() + ".cast"), I);
1272 }
1273
Chris Lattner183b3362004-04-09 19:05:30 +00001274 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001275 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1276 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001277
Chris Lattner183b3362004-04-09 19:05:30 +00001278 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1279 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001280 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1281 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001282 }
1283
1284 Value *Op0 = SO, *Op1 = ConstOperand;
1285 if (!ConstIsRHS)
1286 std::swap(Op0, Op1);
1287 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1289 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1290 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1291 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001292 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001293 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001294 abort();
1295 }
Chris Lattner86102b82005-01-01 16:22:27 +00001296 return IC->InsertNewInstBefore(New, I);
1297}
1298
1299// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1300// constant as the other operand, try to fold the binary operator into the
1301// select arguments. This also works for Cast instructions, which obviously do
1302// not have a second operand.
1303static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1304 InstCombiner *IC) {
1305 // Don't modify shared select instructions
1306 if (!SI->hasOneUse()) return 0;
1307 Value *TV = SI->getOperand(1);
1308 Value *FV = SI->getOperand(2);
1309
1310 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001311 // Bool selects with constant operands can be folded to logical ops.
1312 if (SI->getType() == Type::BoolTy) return 0;
1313
Chris Lattner86102b82005-01-01 16:22:27 +00001314 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1315 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1316
1317 return new SelectInst(SI->getCondition(), SelectTrueVal,
1318 SelectFalseVal);
1319 }
1320 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001321}
1322
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001323
1324/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1325/// node as operand #0, see if we can fold the instruction into the PHI (which
1326/// is only possible if all operands to the PHI are constants).
1327Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1328 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001329 unsigned NumPHIValues = PN->getNumIncomingValues();
1330 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1331 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001332
1333 // Check to see if all of the operands of the PHI are constants. If not, we
1334 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001335 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001336 if (!isa<Constant>(PN->getIncomingValue(i)))
1337 return 0;
1338
1339 // Okay, we can do the transformation: create the new PHI node.
1340 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1341 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001342 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001343 InsertNewInstBefore(NewPN, *PN);
1344
1345 // Next, add all of the operands to the PHI.
1346 if (I.getNumOperands() == 2) {
1347 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001348 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001349 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1350 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1351 PN->getIncomingBlock(i));
1352 }
1353 } else {
1354 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1355 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001356 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001357 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1358 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1359 PN->getIncomingBlock(i));
1360 }
1361 }
1362 return ReplaceInstUsesWith(I, NewPN);
1363}
1364
Chris Lattner113f4f42002-06-25 16:13:24 +00001365Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001366 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001367 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001368
Chris Lattnercf4a9962004-04-10 22:01:55 +00001369 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001370 // X + undef -> undef
1371 if (isa<UndefValue>(RHS))
1372 return ReplaceInstUsesWith(I, RHS);
1373
Chris Lattnercf4a9962004-04-10 22:01:55 +00001374 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001375 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1376 if (RHSC->isNullValue())
1377 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001378 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1379 if (CFP->isExactlyValue(-0.0))
1380 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001381 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001382
Chris Lattnercf4a9962004-04-10 22:01:55 +00001383 // X + (signbit) --> X ^ signbit
1384 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001385 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001386 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001387 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001388 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001389
1390 if (isa<PHINode>(LHS))
1391 if (Instruction *NV = FoldOpIntoPhi(I))
1392 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001393
Chris Lattner330628a2006-01-06 17:59:59 +00001394 ConstantInt *XorRHS = 0;
1395 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001396 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1397 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1398 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1399 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1400
1401 uint64_t C0080Val = 1ULL << 31;
1402 int64_t CFF80Val = -C0080Val;
1403 unsigned Size = 32;
1404 do {
1405 if (TySizeBits > Size) {
1406 bool Found = false;
1407 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1408 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1409 if (RHSSExt == CFF80Val) {
1410 if (XorRHS->getZExtValue() == C0080Val)
1411 Found = true;
1412 } else if (RHSZExt == C0080Val) {
1413 if (XorRHS->getSExtValue() == CFF80Val)
1414 Found = true;
1415 }
1416 if (Found) {
1417 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001418 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001419 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001420 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001421 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001422 Size = 0; // Not a sign ext, but can't be any others either.
1423 goto FoundSExt;
1424 }
1425 }
1426 Size >>= 1;
1427 C0080Val >>= Size;
1428 CFF80Val >>= Size;
1429 } while (Size >= 8);
1430
1431FoundSExt:
1432 const Type *MiddleType = 0;
1433 switch (Size) {
1434 default: break;
1435 case 32: MiddleType = Type::IntTy; break;
1436 case 16: MiddleType = Type::ShortTy; break;
1437 case 8: MiddleType = Type::SByteTy; break;
1438 }
1439 if (MiddleType) {
1440 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1441 InsertNewInstBefore(NewTrunc, I);
1442 return new CastInst(NewTrunc, I.getType());
1443 }
1444 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001445 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001446
Chris Lattnerb8b97502003-08-13 19:01:45 +00001447 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001448 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001449 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001450
1451 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1452 if (RHSI->getOpcode() == Instruction::Sub)
1453 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1454 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1455 }
1456 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1457 if (LHSI->getOpcode() == Instruction::Sub)
1458 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1459 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1460 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001461 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001462
Chris Lattner147e9752002-05-08 22:46:53 +00001463 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001464 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001465 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001466
1467 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001468 if (!isa<Constant>(RHS))
1469 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001470 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001471
Misha Brukmanb1c93172005-04-21 23:48:37 +00001472
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001473 ConstantInt *C2;
1474 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1475 if (X == RHS) // X*C + X --> X * (C+1)
1476 return BinaryOperator::createMul(RHS, AddOne(C2));
1477
1478 // X*C1 + X*C2 --> X * (C1+C2)
1479 ConstantInt *C1;
1480 if (X == dyn_castFoldableMul(RHS, C1))
1481 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001482 }
1483
1484 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001485 if (dyn_castFoldableMul(RHS, C2) == LHS)
1486 return BinaryOperator::createMul(LHS, AddOne(C2));
1487
Chris Lattner57c8d992003-02-18 19:57:07 +00001488
Chris Lattnerb8b97502003-08-13 19:01:45 +00001489 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001490 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001491 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001492
Chris Lattnerb9cde762003-10-02 15:11:26 +00001493 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001494 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001495 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1496 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1497 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001498 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001499
Chris Lattnerbff91d92004-10-08 05:07:56 +00001500 // (X & FF00) + xx00 -> (X+xx00) & FF00
1501 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1502 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1503 if (Anded == CRHS) {
1504 // See if all bits from the first bit set in the Add RHS up are included
1505 // in the mask. First, get the rightmost bit.
1506 uint64_t AddRHSV = CRHS->getRawValue();
1507
1508 // Form a mask of all bits from the lowest bit added through the top.
1509 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001510 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001511
1512 // See if the and mask includes all of these bits.
1513 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001514
Chris Lattnerbff91d92004-10-08 05:07:56 +00001515 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1516 // Okay, the xform is safe. Insert the new add pronto.
1517 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1518 LHS->getName()), I);
1519 return BinaryOperator::createAnd(NewAdd, C2);
1520 }
1521 }
1522 }
1523
Chris Lattnerd4252a72004-07-30 07:50:03 +00001524 // Try to fold constant add into select arguments.
1525 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001526 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001527 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001528 }
1529
Chris Lattner113f4f42002-06-25 16:13:24 +00001530 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001531}
1532
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001533// isSignBit - Return true if the value represented by the constant only has the
1534// highest order bit set.
1535static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001536 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001537 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001538}
1539
Chris Lattner022167f2004-03-13 00:11:49 +00001540/// RemoveNoopCast - Strip off nonconverting casts from the value.
1541///
1542static Value *RemoveNoopCast(Value *V) {
1543 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1544 const Type *CTy = CI->getType();
1545 const Type *OpTy = CI->getOperand(0)->getType();
1546 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001547 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001548 return RemoveNoopCast(CI->getOperand(0));
1549 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1550 return RemoveNoopCast(CI->getOperand(0));
1551 }
1552 return V;
1553}
1554
Chris Lattner113f4f42002-06-25 16:13:24 +00001555Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001557
Chris Lattnere6794492002-08-12 21:17:25 +00001558 if (Op0 == Op1) // sub X, X -> 0
1559 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001560
Chris Lattnere6794492002-08-12 21:17:25 +00001561 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001562 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001563 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001564
Chris Lattner81a7a232004-10-16 18:11:37 +00001565 if (isa<UndefValue>(Op0))
1566 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1567 if (isa<UndefValue>(Op1))
1568 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1569
Chris Lattner8f2f5982003-11-05 01:06:05 +00001570 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1571 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001572 if (C->isAllOnesValue())
1573 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001574
Chris Lattner8f2f5982003-11-05 01:06:05 +00001575 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001576 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001577 if (match(Op1, m_Not(m_Value(X))))
1578 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001579 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001580 // -((uint)X >> 31) -> ((int)X >> 31)
1581 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001582 if (C->isNullValue()) {
1583 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1584 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001585 if (SI->getOpcode() == Instruction::Shr)
1586 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1587 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001588 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001589 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001590 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001591 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001592 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001593 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001594 // Ok, the transformation is safe. Insert a cast of the incoming
1595 // value, then the new shift, then the new cast.
1596 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1597 SI->getOperand(0)->getName());
1598 Value *InV = InsertNewInstBefore(FirstCast, I);
1599 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1600 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001601 if (NewShift->getType() == I.getType())
1602 return NewShift;
1603 else {
1604 InV = InsertNewInstBefore(NewShift, I);
1605 return new CastInst(NewShift, I.getType());
1606 }
Chris Lattner92295c52004-03-12 23:53:13 +00001607 }
1608 }
Chris Lattner022167f2004-03-13 00:11:49 +00001609 }
Chris Lattner183b3362004-04-09 19:05:30 +00001610
1611 // Try to fold constant sub into select arguments.
1612 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001613 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001614 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001615
1616 if (isa<PHINode>(Op0))
1617 if (Instruction *NV = FoldOpIntoPhi(I))
1618 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001619 }
1620
Chris Lattnera9be4492005-04-07 16:15:25 +00001621 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1622 if (Op1I->getOpcode() == Instruction::Add &&
1623 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001624 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001625 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001626 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001627 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001628 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1629 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1630 // C1-(X+C2) --> (C1-C2)-X
1631 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1632 Op1I->getOperand(0));
1633 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001634 }
1635
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001636 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001637 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1638 // is not used by anyone else...
1639 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001640 if (Op1I->getOpcode() == Instruction::Sub &&
1641 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001642 // Swap the two operands of the subexpr...
1643 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1644 Op1I->setOperand(0, IIOp1);
1645 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001646
Chris Lattner3082c5a2003-02-18 19:28:33 +00001647 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001648 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001649 }
1650
1651 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1652 //
1653 if (Op1I->getOpcode() == Instruction::And &&
1654 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1655 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1656
Chris Lattner396dbfe2004-06-09 05:08:07 +00001657 Value *NewNot =
1658 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001659 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001660 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001661
Chris Lattner0aee4b72004-10-06 15:08:25 +00001662 // -(X sdiv C) -> (X sdiv -C)
1663 if (Op1I->getOpcode() == Instruction::Div)
1664 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001665 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001666 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001667 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001668 ConstantExpr::getNeg(DivRHS));
1669
Chris Lattner57c8d992003-02-18 19:57:07 +00001670 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001671 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001672 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001673 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001674 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001675 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001676 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001677 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001678 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001679
Chris Lattner47060462005-04-07 17:14:51 +00001680 if (!Op0->getType()->isFloatingPoint())
1681 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1682 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001683 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1684 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1685 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1686 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001687 } else if (Op0I->getOpcode() == Instruction::Sub) {
1688 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1689 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001690 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001691
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001692 ConstantInt *C1;
1693 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1694 if (X == Op1) { // X*C - X --> X * (C-1)
1695 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1696 return BinaryOperator::createMul(Op1, CP1);
1697 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001698
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001699 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1700 if (X == dyn_castFoldableMul(Op1, C2))
1701 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1702 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001703 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001704}
1705
Chris Lattnere79e8542004-02-23 06:38:22 +00001706/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1707/// really just returns true if the most significant (sign) bit is set.
1708static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1709 if (RHS->getType()->isSigned()) {
1710 // True if source is LHS < 0 or LHS <= -1
1711 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1712 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1713 } else {
1714 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1715 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1716 // the size of the integer type.
1717 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001718 return RHSC->getValue() ==
1719 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001720 if (Opcode == Instruction::SetGT)
1721 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001722 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001723 }
1724 return false;
1725}
1726
Chris Lattner113f4f42002-06-25 16:13:24 +00001727Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001728 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001729 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001730
Chris Lattner81a7a232004-10-16 18:11:37 +00001731 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1732 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1733
Chris Lattnere6794492002-08-12 21:17:25 +00001734 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001735 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1736 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001737
1738 // ((X << C1)*C2) == (X * (C2 << C1))
1739 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1740 if (SI->getOpcode() == Instruction::Shl)
1741 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001742 return BinaryOperator::createMul(SI->getOperand(0),
1743 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001744
Chris Lattnercce81be2003-09-11 22:24:54 +00001745 if (CI->isNullValue())
1746 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1747 if (CI->equalsInt(1)) // X * 1 == X
1748 return ReplaceInstUsesWith(I, Op0);
1749 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001750 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001751
Chris Lattnercce81be2003-09-11 22:24:54 +00001752 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001753 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1754 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001755 return new ShiftInst(Instruction::Shl, Op0,
1756 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001757 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001758 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001759 if (Op1F->isNullValue())
1760 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001761
Chris Lattner3082c5a2003-02-18 19:28:33 +00001762 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1763 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1764 if (Op1F->getValue() == 1.0)
1765 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1766 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001767
1768 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1769 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1770 isa<ConstantInt>(Op0I->getOperand(1))) {
1771 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1772 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1773 Op1, "tmp");
1774 InsertNewInstBefore(Add, I);
1775 Value *C1C2 = ConstantExpr::getMul(Op1,
1776 cast<Constant>(Op0I->getOperand(1)));
1777 return BinaryOperator::createAdd(Add, C1C2);
1778
1779 }
Chris Lattner183b3362004-04-09 19:05:30 +00001780
1781 // Try to fold constant mul into select arguments.
1782 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001783 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001784 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001785
1786 if (isa<PHINode>(Op0))
1787 if (Instruction *NV = FoldOpIntoPhi(I))
1788 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001789 }
1790
Chris Lattner934a64cf2003-03-10 23:23:04 +00001791 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1792 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001793 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001794
Chris Lattner2635b522004-02-23 05:39:21 +00001795 // If one of the operands of the multiply is a cast from a boolean value, then
1796 // we know the bool is either zero or one, so this is a 'masking' multiply.
1797 // See if we can simplify things based on how the boolean was originally
1798 // formed.
1799 CastInst *BoolCast = 0;
1800 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1801 if (CI->getOperand(0)->getType() == Type::BoolTy)
1802 BoolCast = CI;
1803 if (!BoolCast)
1804 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1805 if (CI->getOperand(0)->getType() == Type::BoolTy)
1806 BoolCast = CI;
1807 if (BoolCast) {
1808 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1809 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1810 const Type *SCOpTy = SCIOp0->getType();
1811
Chris Lattnere79e8542004-02-23 06:38:22 +00001812 // If the setcc is true iff the sign bit of X is set, then convert this
1813 // multiply into a shift/and combination.
1814 if (isa<ConstantInt>(SCIOp1) &&
1815 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001816 // Shift the X value right to turn it into "all signbits".
1817 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001818 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001819 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001820 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001821 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1822 SCIOp0->getName()), I);
1823 }
1824
1825 Value *V =
1826 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1827 BoolCast->getOperand(0)->getName()+
1828 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001829
1830 // If the multiply type is not the same as the source type, sign extend
1831 // or truncate to the multiply type.
1832 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001833 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001834
Chris Lattner2635b522004-02-23 05:39:21 +00001835 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001836 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001837 }
1838 }
1839 }
1840
Chris Lattner113f4f42002-06-25 16:13:24 +00001841 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001842}
1843
Chris Lattner113f4f42002-06-25 16:13:24 +00001844Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001846
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001847 if (isa<UndefValue>(Op0)) // undef / X -> 0
1848 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1849 if (isa<UndefValue>(Op1))
1850 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1851
1852 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001853 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001854 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001855 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001856
Chris Lattnere20c3342004-04-26 14:01:59 +00001857 // div X, -1 == -X
1858 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001859 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001860
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001861 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001862 if (LHS->getOpcode() == Instruction::Div)
1863 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001864 // (X / C1) / C2 -> X / (C1*C2)
1865 return BinaryOperator::createDiv(LHS->getOperand(0),
1866 ConstantExpr::getMul(RHS, LHSRHS));
1867 }
1868
Chris Lattner3082c5a2003-02-18 19:28:33 +00001869 // Check to see if this is an unsigned division with an exact power of 2,
1870 // if so, convert to a right shift.
1871 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1872 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001873 if (isPowerOf2_64(Val)) {
1874 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001875 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001876 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001877 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001878
Chris Lattner4ad08352004-10-09 02:50:40 +00001879 // -X/C -> X/-C
1880 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001881 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001882 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1883
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001884 if (!RHS->isNullValue()) {
1885 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001886 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001887 return R;
1888 if (isa<PHINode>(Op0))
1889 if (Instruction *NV = FoldOpIntoPhi(I))
1890 return NV;
1891 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001892 }
1893
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001894 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1895 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1896 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1897 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1898 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1899 if (STO->getValue() == 0) { // Couldn't be this argument.
1900 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001901 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001902 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001903 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001904 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001905 }
1906
Chris Lattner42362612005-04-08 04:03:26 +00001907 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001908 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1909 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001910 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1911 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1912 TC, SI->getName()+".t");
1913 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001914
Chris Lattner42362612005-04-08 04:03:26 +00001915 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1916 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1917 FC, SI->getName()+".f");
1918 FSI = InsertNewInstBefore(FSI, I);
1919 return new SelectInst(SI->getOperand(0), TSI, FSI);
1920 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001921 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001922
Chris Lattner3082c5a2003-02-18 19:28:33 +00001923 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001924 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001925 if (LHS->equalsInt(0))
1926 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1927
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001928 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001929 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001930 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001931 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1932 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001933 const Type *NTy = Op0->getType()->getUnsignedVersion();
1934 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1935 InsertNewInstBefore(LHS, I);
1936 Value *RHS;
1937 if (Constant *R = dyn_cast<Constant>(Op1))
1938 RHS = ConstantExpr::getCast(R, NTy);
1939 else
1940 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1941 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1942 InsertNewInstBefore(Div, I);
1943 return new CastInst(Div, I.getType());
1944 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001945 } else {
1946 // Known to be an unsigned division.
1947 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1948 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1949 if (RHSI->getOpcode() == Instruction::Shl &&
1950 isa<ConstantUInt>(RHSI->getOperand(0))) {
1951 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1952 if (isPowerOf2_64(C1)) {
1953 unsigned C2 = Log2_64(C1);
1954 Value *Add = RHSI->getOperand(1);
1955 if (C2) {
1956 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1957 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1958 "tmp"), I);
1959 }
1960 return new ShiftInst(Instruction::Shr, Op0, Add);
1961 }
1962 }
1963 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001964 }
1965
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001966 return 0;
1967}
1968
1969
Chris Lattner85dda9a2006-03-02 06:50:58 +00001970/// GetFactor - If we can prove that the specified value is at least a multiple
1971/// of some factor, return that factor.
1972static Constant *GetFactor(Value *V) {
1973 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1974 return CI;
1975
1976 // Unless we can be tricky, we know this is a multiple of 1.
1977 Constant *Result = ConstantInt::get(V->getType(), 1);
1978
1979 Instruction *I = dyn_cast<Instruction>(V);
1980 if (!I) return Result;
1981
1982 if (I->getOpcode() == Instruction::Mul) {
1983 // Handle multiplies by a constant, etc.
1984 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1985 GetFactor(I->getOperand(1)));
1986 } else if (I->getOpcode() == Instruction::Shl) {
1987 // (X<<C) -> X * (1 << C)
1988 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1989 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1990 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1991 }
1992 } else if (I->getOpcode() == Instruction::And) {
1993 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1994 // X & 0xFFF0 is known to be a multiple of 16.
1995 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1996 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1997 return ConstantExpr::getShl(Result,
1998 ConstantUInt::get(Type::UByteTy, Zeros));
1999 }
2000 } else if (I->getOpcode() == Instruction::Cast) {
2001 Value *Op = I->getOperand(0);
2002 // Only handle int->int casts.
2003 if (!Op->getType()->isInteger()) return Result;
2004 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2005 }
2006 return Result;
2007}
2008
Chris Lattner113f4f42002-06-25 16:13:24 +00002009Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002011
2012 // 0 % X == 0, we don't need to preserve faults!
2013 if (Constant *LHS = dyn_cast<Constant>(Op0))
2014 if (LHS->isNullValue())
2015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2016
2017 if (isa<UndefValue>(Op0)) // undef % X -> 0
2018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2019 if (isa<UndefValue>(Op1))
2020 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2021
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002022 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002023 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002024 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002025 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002026 // X % -Y -> X % Y
2027 AddUsesToWorkList(I);
2028 I.setOperand(1, RHSNeg);
2029 return &I;
2030 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002031
2032 // If the top bits of both operands are zero (i.e. we can prove they are
2033 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002034 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2035 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002036 const Type *NTy = Op0->getType()->getUnsignedVersion();
2037 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2038 InsertNewInstBefore(LHS, I);
2039 Value *RHS;
2040 if (Constant *R = dyn_cast<Constant>(Op1))
2041 RHS = ConstantExpr::getCast(R, NTy);
2042 else
2043 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2044 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2045 InsertNewInstBefore(Rem, I);
2046 return new CastInst(Rem, I.getType());
2047 }
2048 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002049
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002050 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002051 // X % 0 == undef, we don't need to preserve faults!
2052 if (RHS->equalsInt(0))
2053 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2054
Chris Lattner3082c5a2003-02-18 19:28:33 +00002055 if (RHS->equalsInt(1)) // X % 1 == 0
2056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2057
2058 // Check to see if this is an unsigned remainder with an exact power of 2,
2059 // if so, convert to a bitwise and.
2060 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002061 if (isPowerOf2_64(C->getValue()))
2062 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002063
Chris Lattnerb70f1412006-02-28 05:49:21 +00002064 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2065 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2066 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2067 return R;
2068 } else if (isa<PHINode>(Op0I)) {
2069 if (Instruction *NV = FoldOpIntoPhi(I))
2070 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002071 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002072
2073 // X*C1%C2 --> 0 iff C1%C2 == 0
2074 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2075 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002076 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002077 }
2078
Chris Lattner2e90b732006-02-05 07:54:04 +00002079 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2080 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2081 if (I.getType()->isUnsigned() &&
2082 RHSI->getOpcode() == Instruction::Shl &&
2083 isa<ConstantUInt>(RHSI->getOperand(0))) {
2084 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2085 if (isPowerOf2_64(C1)) {
2086 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2087 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2088 "tmp"), I);
2089 return BinaryOperator::createAnd(Op0, Add);
2090 }
2091 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002092
2093 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2094 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2095 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2096 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2097 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2098 if (STO->getValue() == 0) { // Couldn't be this argument.
2099 I.setOperand(1, SFO);
2100 return &I;
2101 } else if (SFO->getValue() == 0) {
2102 I.setOperand(1, STO);
2103 return &I;
2104 }
2105
2106 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2107 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2108 SubOne(STO), SI->getName()+".t"), I);
2109 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2110 SubOne(SFO), SI->getName()+".f"), I);
2111 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2112 }
2113 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002114 }
2115
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002116 return 0;
2117}
2118
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002119// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002120static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002121 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2122 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002123
2124 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002125
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002126 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002127 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002128 int64_t Val = INT64_MAX; // All ones
2129 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2130 return CS->getValue() == Val-1;
2131}
2132
2133// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002134static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002135 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2136 return CU->getValue() == 1;
2137
2138 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002139
2140 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002141 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002142 int64_t Val = -1; // All ones
2143 Val <<= TypeBits-1; // Shift over to the right spot
2144 return CS->getValue() == Val+1;
2145}
2146
Chris Lattner35167c32004-06-09 07:59:58 +00002147// isOneBitSet - Return true if there is exactly one bit set in the specified
2148// constant.
2149static bool isOneBitSet(const ConstantInt *CI) {
2150 uint64_t V = CI->getRawValue();
2151 return V && (V & (V-1)) == 0;
2152}
2153
Chris Lattner8fc5af42004-09-23 21:46:38 +00002154#if 0 // Currently unused
2155// isLowOnes - Return true if the constant is of the form 0+1+.
2156static bool isLowOnes(const ConstantInt *CI) {
2157 uint64_t V = CI->getRawValue();
2158
2159 // There won't be bits set in parts that the type doesn't contain.
2160 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2161
2162 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2163 return U && V && (U & V) == 0;
2164}
2165#endif
2166
2167// isHighOnes - Return true if the constant is of the form 1+0+.
2168// This is the same as lowones(~X).
2169static bool isHighOnes(const ConstantInt *CI) {
2170 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002171 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002172
2173 // There won't be bits set in parts that the type doesn't contain.
2174 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2175
2176 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2177 return U && V && (U & V) == 0;
2178}
2179
2180
Chris Lattner3ac7c262003-08-13 20:16:26 +00002181/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2182/// are carefully arranged to allow folding of expressions such as:
2183///
2184/// (A < B) | (A > B) --> (A != B)
2185///
2186/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2187/// represents that the comparison is true if A == B, and bit value '1' is true
2188/// if A < B.
2189///
2190static unsigned getSetCondCode(const SetCondInst *SCI) {
2191 switch (SCI->getOpcode()) {
2192 // False -> 0
2193 case Instruction::SetGT: return 1;
2194 case Instruction::SetEQ: return 2;
2195 case Instruction::SetGE: return 3;
2196 case Instruction::SetLT: return 4;
2197 case Instruction::SetNE: return 5;
2198 case Instruction::SetLE: return 6;
2199 // True -> 7
2200 default:
2201 assert(0 && "Invalid SetCC opcode!");
2202 return 0;
2203 }
2204}
2205
2206/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2207/// opcode and two operands into either a constant true or false, or a brand new
2208/// SetCC instruction.
2209static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2210 switch (Opcode) {
2211 case 0: return ConstantBool::False;
2212 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2213 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2214 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2215 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2216 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2217 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2218 case 7: return ConstantBool::True;
2219 default: assert(0 && "Illegal SetCCCode!"); return 0;
2220 }
2221}
2222
2223// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2224struct FoldSetCCLogical {
2225 InstCombiner &IC;
2226 Value *LHS, *RHS;
2227 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2228 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2229 bool shouldApply(Value *V) const {
2230 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2231 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2232 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2233 return false;
2234 }
2235 Instruction *apply(BinaryOperator &Log) const {
2236 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2237 if (SCI->getOperand(0) != LHS) {
2238 assert(SCI->getOperand(1) == LHS);
2239 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2240 }
2241
2242 unsigned LHSCode = getSetCondCode(SCI);
2243 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2244 unsigned Code;
2245 switch (Log.getOpcode()) {
2246 case Instruction::And: Code = LHSCode & RHSCode; break;
2247 case Instruction::Or: Code = LHSCode | RHSCode; break;
2248 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002249 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002250 }
2251
2252 Value *RV = getSetCCValue(Code, LHS, RHS);
2253 if (Instruction *I = dyn_cast<Instruction>(RV))
2254 return I;
2255 // Otherwise, it's a constant boolean value...
2256 return IC.ReplaceInstUsesWith(Log, RV);
2257 }
2258};
2259
Chris Lattnerba1cb382003-09-19 17:17:26 +00002260// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2261// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2262// guaranteed to be either a shift instruction or a binary operator.
2263Instruction *InstCombiner::OptAndOp(Instruction *Op,
2264 ConstantIntegral *OpRHS,
2265 ConstantIntegral *AndRHS,
2266 BinaryOperator &TheAnd) {
2267 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002268 Constant *Together = 0;
2269 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002270 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002271
Chris Lattnerba1cb382003-09-19 17:17:26 +00002272 switch (Op->getOpcode()) {
2273 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002274 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002275 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2276 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002277 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002278 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002279 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002280 }
2281 break;
2282 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002283 if (Together == AndRHS) // (X | C) & C --> C
2284 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002285
Chris Lattner86102b82005-01-01 16:22:27 +00002286 if (Op->hasOneUse() && Together != OpRHS) {
2287 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2288 std::string Op0Name = Op->getName(); Op->setName("");
2289 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2290 InsertNewInstBefore(Or, TheAnd);
2291 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002292 }
2293 break;
2294 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002295 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002296 // Adding a one to a single bit bit-field should be turned into an XOR
2297 // of the bit. First thing to check is to see if this AND is with a
2298 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002299 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002300
2301 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002302 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002303
2304 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002305 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002306 // Ok, at this point, we know that we are masking the result of the
2307 // ADD down to exactly one bit. If the constant we are adding has
2308 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002309 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002310
Chris Lattnerba1cb382003-09-19 17:17:26 +00002311 // Check to see if any bits below the one bit set in AndRHSV are set.
2312 if ((AddRHS & (AndRHSV-1)) == 0) {
2313 // If not, the only thing that can effect the output of the AND is
2314 // the bit specified by AndRHSV. If that bit is set, the effect of
2315 // the XOR is to toggle the bit. If it is clear, then the ADD has
2316 // no effect.
2317 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2318 TheAnd.setOperand(0, X);
2319 return &TheAnd;
2320 } else {
2321 std::string Name = Op->getName(); Op->setName("");
2322 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002323 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002324 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002325 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002326 }
2327 }
2328 }
2329 }
2330 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002331
2332 case Instruction::Shl: {
2333 // We know that the AND will not produce any of the bits shifted in, so if
2334 // the anded constant includes them, clear them now!
2335 //
2336 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002337 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2338 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002339
Chris Lattner7e794272004-09-24 15:21:34 +00002340 if (CI == ShlMask) { // Masking out bits that the shift already masks
2341 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2342 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002343 TheAnd.setOperand(1, CI);
2344 return &TheAnd;
2345 }
2346 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002347 }
Chris Lattner2da29172003-09-19 19:05:02 +00002348 case Instruction::Shr:
2349 // We know that the AND will not produce any of the bits shifted in, so if
2350 // the anded constant includes them, clear them now! This only applies to
2351 // unsigned shifts, because a signed shr may bring in set bits!
2352 //
2353 if (AndRHS->getType()->isUnsigned()) {
2354 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002355 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2356 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2357
2358 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2359 return ReplaceInstUsesWith(TheAnd, Op);
2360 } else if (CI != AndRHS) {
2361 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002362 return &TheAnd;
2363 }
Chris Lattner7e794272004-09-24 15:21:34 +00002364 } else { // Signed shr.
2365 // See if this is shifting in some sign extension, then masking it out
2366 // with an and.
2367 if (Op->hasOneUse()) {
2368 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2369 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2370 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002371 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002372 // Make the argument unsigned.
2373 Value *ShVal = Op->getOperand(0);
2374 ShVal = InsertCastBefore(ShVal,
2375 ShVal->getType()->getUnsignedVersion(),
2376 TheAnd);
2377 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2378 OpRHS, Op->getName()),
2379 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002380 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2381 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2382 TheAnd.getName()),
2383 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002384 return new CastInst(ShVal, Op->getType());
2385 }
2386 }
Chris Lattner2da29172003-09-19 19:05:02 +00002387 }
2388 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002389 }
2390 return 0;
2391}
2392
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002393
Chris Lattner6862fbd2004-09-29 17:40:11 +00002394/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2395/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2396/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2397/// insert new instructions.
2398Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2399 bool Inside, Instruction &IB) {
2400 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2401 "Lo is not <= Hi in range emission code!");
2402 if (Inside) {
2403 if (Lo == Hi) // Trivially false.
2404 return new SetCondInst(Instruction::SetNE, V, V);
2405 if (cast<ConstantIntegral>(Lo)->isMinValue())
2406 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002407
Chris Lattner6862fbd2004-09-29 17:40:11 +00002408 Constant *AddCST = ConstantExpr::getNeg(Lo);
2409 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2410 InsertNewInstBefore(Add, IB);
2411 // Convert to unsigned for the comparison.
2412 const Type *UnsType = Add->getType()->getUnsignedVersion();
2413 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2414 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2415 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2416 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2417 }
2418
2419 if (Lo == Hi) // Trivially true.
2420 return new SetCondInst(Instruction::SetEQ, V, V);
2421
2422 Hi = SubOne(cast<ConstantInt>(Hi));
2423 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2424 return new SetCondInst(Instruction::SetGT, V, Hi);
2425
2426 // Emit X-Lo > Hi-Lo-1
2427 Constant *AddCST = ConstantExpr::getNeg(Lo);
2428 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2429 InsertNewInstBefore(Add, IB);
2430 // Convert to unsigned for the comparison.
2431 const Type *UnsType = Add->getType()->getUnsignedVersion();
2432 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2433 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2434 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2435 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2436}
2437
Chris Lattnerb4b25302005-09-18 07:22:02 +00002438// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2439// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2440// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2441// not, since all 1s are not contiguous.
2442static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2443 uint64_t V = Val->getRawValue();
2444 if (!isShiftedMask_64(V)) return false;
2445
2446 // look for the first zero bit after the run of ones
2447 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2448 // look for the first non-zero bit
2449 ME = 64-CountLeadingZeros_64(V);
2450 return true;
2451}
2452
2453
2454
2455/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2456/// where isSub determines whether the operator is a sub. If we can fold one of
2457/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002458///
2459/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2460/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2461/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2462///
2463/// return (A +/- B).
2464///
2465Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2466 ConstantIntegral *Mask, bool isSub,
2467 Instruction &I) {
2468 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2469 if (!LHSI || LHSI->getNumOperands() != 2 ||
2470 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2471
2472 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2473
2474 switch (LHSI->getOpcode()) {
2475 default: return 0;
2476 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002477 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2478 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2479 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2480 break;
2481
2482 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2483 // part, we don't need any explicit masks to take them out of A. If that
2484 // is all N is, ignore it.
2485 unsigned MB, ME;
2486 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002487 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2488 Mask >>= 64-MB+1;
2489 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002490 break;
2491 }
2492 }
Chris Lattneraf517572005-09-18 04:24:45 +00002493 return 0;
2494 case Instruction::Or:
2495 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002496 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2497 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2498 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002499 break;
2500 return 0;
2501 }
2502
2503 Instruction *New;
2504 if (isSub)
2505 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2506 else
2507 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2508 return InsertNewInstBefore(New, I);
2509}
2510
Chris Lattner113f4f42002-06-25 16:13:24 +00002511Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002512 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002514
Chris Lattner81a7a232004-10-16 18:11:37 +00002515 if (isa<UndefValue>(Op1)) // X & undef -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
Chris Lattner86102b82005-01-01 16:22:27 +00002518 // and X, X = X
2519 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002520 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002521
Chris Lattner5b2edb12006-02-12 08:02:11 +00002522 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002523 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002524 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002525 if (!isa<PackedType>(I.getType()) &&
2526 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002527 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002528 return &I;
2529
Chris Lattner86102b82005-01-01 16:22:27 +00002530 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002531 uint64_t AndRHSMask = AndRHS->getZExtValue();
2532 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002533 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002534
Chris Lattnerba1cb382003-09-19 17:17:26 +00002535 // Optimize a variety of ((val OP C1) & C2) combinations...
2536 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2537 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002538 Value *Op0LHS = Op0I->getOperand(0);
2539 Value *Op0RHS = Op0I->getOperand(1);
2540 switch (Op0I->getOpcode()) {
2541 case Instruction::Xor:
2542 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002543 // If the mask is only needed on one incoming arm, push it up.
2544 if (Op0I->hasOneUse()) {
2545 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2546 // Not masking anything out for the LHS, move to RHS.
2547 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2548 Op0RHS->getName()+".masked");
2549 InsertNewInstBefore(NewRHS, I);
2550 return BinaryOperator::create(
2551 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002552 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002553 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002554 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2555 // Not masking anything out for the RHS, move to LHS.
2556 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2557 Op0LHS->getName()+".masked");
2558 InsertNewInstBefore(NewLHS, I);
2559 return BinaryOperator::create(
2560 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2561 }
2562 }
2563
Chris Lattner86102b82005-01-01 16:22:27 +00002564 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002565 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002566 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2567 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2568 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2569 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2570 return BinaryOperator::createAnd(V, AndRHS);
2571 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2572 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002573 break;
2574
2575 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002576 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2577 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2578 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2579 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2580 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002581 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002582 }
2583
Chris Lattner16464b32003-07-23 19:25:52 +00002584 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002585 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002586 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002587 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2588 const Type *SrcTy = CI->getOperand(0)->getType();
2589
Chris Lattner2c14cf72005-08-07 07:03:10 +00002590 // If this is an integer truncation or change from signed-to-unsigned, and
2591 // if the source is an and/or with immediate, transform it. This
2592 // frequently occurs for bitfield accesses.
2593 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2594 if (SrcTy->getPrimitiveSizeInBits() >=
2595 I.getType()->getPrimitiveSizeInBits() &&
2596 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002597 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002598 if (CastOp->getOpcode() == Instruction::And) {
2599 // Change: and (cast (and X, C1) to T), C2
2600 // into : and (cast X to T), trunc(C1)&C2
2601 // This will folds the two ands together, which may allow other
2602 // simplifications.
2603 Instruction *NewCast =
2604 new CastInst(CastOp->getOperand(0), I.getType(),
2605 CastOp->getName()+".shrunk");
2606 NewCast = InsertNewInstBefore(NewCast, I);
2607
2608 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2609 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2610 return BinaryOperator::createAnd(NewCast, C3);
2611 } else if (CastOp->getOpcode() == Instruction::Or) {
2612 // Change: and (cast (or X, C1) to T), C2
2613 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2614 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2615 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2616 return ReplaceInstUsesWith(I, AndRHS);
2617 }
2618 }
Chris Lattner33217db2003-07-23 19:36:21 +00002619 }
Chris Lattner183b3362004-04-09 19:05:30 +00002620
2621 // Try to fold constant and into select arguments.
2622 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002623 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002624 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002625 if (isa<PHINode>(Op0))
2626 if (Instruction *NV = FoldOpIntoPhi(I))
2627 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002628 }
2629
Chris Lattnerbb74e222003-03-10 23:06:50 +00002630 Value *Op0NotVal = dyn_castNotVal(Op0);
2631 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002632
Chris Lattner023a4832004-06-18 06:07:51 +00002633 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2634 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2635
Misha Brukman9c003d82004-07-30 12:50:08 +00002636 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002637 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002638 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2639 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002640 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002641 return BinaryOperator::createNot(Or);
2642 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002643
2644 {
2645 Value *A = 0, *B = 0;
2646 ConstantInt *C1 = 0, *C2 = 0;
2647 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2648 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2649 return ReplaceInstUsesWith(I, Op1);
2650 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2651 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2652 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002653
2654 if (Op0->hasOneUse() &&
2655 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2656 if (A == Op1) { // (A^B)&A -> A&(A^B)
2657 I.swapOperands(); // Simplify below
2658 std::swap(Op0, Op1);
2659 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2660 cast<BinaryOperator>(Op0)->swapOperands();
2661 I.swapOperands(); // Simplify below
2662 std::swap(Op0, Op1);
2663 }
2664 }
2665 if (Op1->hasOneUse() &&
2666 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2667 if (B == Op0) { // B&(A^B) -> B&(B^A)
2668 cast<BinaryOperator>(Op1)->swapOperands();
2669 std::swap(A, B);
2670 }
2671 if (A == Op0) { // A&(A^B) -> A & ~B
2672 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2673 InsertNewInstBefore(NotB, I);
2674 return BinaryOperator::createAnd(A, NotB);
2675 }
2676 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002677 }
2678
Chris Lattner3082c5a2003-02-18 19:28:33 +00002679
Chris Lattner623826c2004-09-28 21:48:02 +00002680 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2681 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002682 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2683 return R;
2684
Chris Lattner623826c2004-09-28 21:48:02 +00002685 Value *LHSVal, *RHSVal;
2686 ConstantInt *LHSCst, *RHSCst;
2687 Instruction::BinaryOps LHSCC, RHSCC;
2688 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2689 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2690 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2691 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002692 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002693 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2694 // Ensure that the larger constant is on the RHS.
2695 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2696 SetCondInst *LHS = cast<SetCondInst>(Op0);
2697 if (cast<ConstantBool>(Cmp)->getValue()) {
2698 std::swap(LHS, RHS);
2699 std::swap(LHSCst, RHSCst);
2700 std::swap(LHSCC, RHSCC);
2701 }
2702
2703 // At this point, we know we have have two setcc instructions
2704 // comparing a value against two constants and and'ing the result
2705 // together. Because of the above check, we know that we only have
2706 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2707 // FoldSetCCLogical check above), that the two constants are not
2708 // equal.
2709 assert(LHSCst != RHSCst && "Compares not folded above?");
2710
2711 switch (LHSCC) {
2712 default: assert(0 && "Unknown integer condition code!");
2713 case Instruction::SetEQ:
2714 switch (RHSCC) {
2715 default: assert(0 && "Unknown integer condition code!");
2716 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2717 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2718 return ReplaceInstUsesWith(I, ConstantBool::False);
2719 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2720 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2721 return ReplaceInstUsesWith(I, LHS);
2722 }
2723 case Instruction::SetNE:
2724 switch (RHSCC) {
2725 default: assert(0 && "Unknown integer condition code!");
2726 case Instruction::SetLT:
2727 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2728 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2729 break; // (X != 13 & X < 15) -> no change
2730 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2731 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2732 return ReplaceInstUsesWith(I, RHS);
2733 case Instruction::SetNE:
2734 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2735 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2736 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2737 LHSVal->getName()+".off");
2738 InsertNewInstBefore(Add, I);
2739 const Type *UnsType = Add->getType()->getUnsignedVersion();
2740 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2741 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2742 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2743 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2744 }
2745 break; // (X != 13 & X != 15) -> no change
2746 }
2747 break;
2748 case Instruction::SetLT:
2749 switch (RHSCC) {
2750 default: assert(0 && "Unknown integer condition code!");
2751 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2752 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2753 return ReplaceInstUsesWith(I, ConstantBool::False);
2754 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2755 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2756 return ReplaceInstUsesWith(I, LHS);
2757 }
2758 case Instruction::SetGT:
2759 switch (RHSCC) {
2760 default: assert(0 && "Unknown integer condition code!");
2761 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2762 return ReplaceInstUsesWith(I, LHS);
2763 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2764 return ReplaceInstUsesWith(I, RHS);
2765 case Instruction::SetNE:
2766 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2767 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2768 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002769 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2770 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002771 }
2772 }
2773 }
2774 }
2775
Chris Lattner3af10532006-05-05 06:39:07 +00002776 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2777 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002778 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002779 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002780 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002781 // Only do this if the casts both really cause code to be generated.
2782 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2783 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002784 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2785 Op1C->getOperand(0),
2786 I.getName());
2787 InsertNewInstBefore(NewOp, I);
2788 return new CastInst(NewOp, I.getType());
2789 }
2790 }
2791
Chris Lattner113f4f42002-06-25 16:13:24 +00002792 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002793}
2794
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002795/// CollectBSwapParts - Look to see if the specified value defines a single byte
2796/// in the result. If it does, and if the specified byte hasn't been filled in
2797/// yet, fill it in and return false.
2798static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2799 Instruction *I = dyn_cast<Instruction>(V);
2800 if (I == 0) return true;
2801
2802 // If this is an or instruction, it is an inner node of the bswap.
2803 if (I->getOpcode() == Instruction::Or)
2804 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2805 CollectBSwapParts(I->getOperand(1), ByteValues);
2806
2807 // If this is a shift by a constant int, and it is "24", then its operand
2808 // defines a byte. We only handle unsigned types here.
2809 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2810 // Not shifting the entire input by N-1 bytes?
2811 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2812 8*(ByteValues.size()-1))
2813 return true;
2814
2815 unsigned DestNo;
2816 if (I->getOpcode() == Instruction::Shl) {
2817 // X << 24 defines the top byte with the lowest of the input bytes.
2818 DestNo = ByteValues.size()-1;
2819 } else {
2820 // X >>u 24 defines the low byte with the highest of the input bytes.
2821 DestNo = 0;
2822 }
2823
2824 // If the destination byte value is already defined, the values are or'd
2825 // together, which isn't a bswap (unless it's an or of the same bits).
2826 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2827 return true;
2828 ByteValues[DestNo] = I->getOperand(0);
2829 return false;
2830 }
2831
2832 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2833 // don't have this.
2834 Value *Shift = 0, *ShiftLHS = 0;
2835 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2836 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2837 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2838 return true;
2839 Instruction *SI = cast<Instruction>(Shift);
2840
2841 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2842 if (ShiftAmt->getRawValue() & 7 ||
2843 ShiftAmt->getRawValue() > 8*ByteValues.size())
2844 return true;
2845
2846 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2847 unsigned DestByte;
2848 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2849 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2850 break;
2851 // Unknown mask for bswap.
2852 if (DestByte == ByteValues.size()) return true;
2853
2854 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2855 unsigned SrcByte;
2856 if (SI->getOpcode() == Instruction::Shl)
2857 SrcByte = DestByte - ShiftBytes;
2858 else
2859 SrcByte = DestByte + ShiftBytes;
2860
2861 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2862 if (SrcByte != ByteValues.size()-DestByte-1)
2863 return true;
2864
2865 // If the destination byte value is already defined, the values are or'd
2866 // together, which isn't a bswap (unless it's an or of the same bits).
2867 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2868 return true;
2869 ByteValues[DestByte] = SI->getOperand(0);
2870 return false;
2871}
2872
2873/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2874/// If so, insert the new bswap intrinsic and return it.
2875Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2876 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2877 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2878 return 0;
2879
2880 /// ByteValues - For each byte of the result, we keep track of which value
2881 /// defines each byte.
2882 std::vector<Value*> ByteValues;
2883 ByteValues.resize(I.getType()->getPrimitiveSize());
2884
2885 // Try to find all the pieces corresponding to the bswap.
2886 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
2887 CollectBSwapParts(I.getOperand(1), ByteValues))
2888 return 0;
2889
2890 // Check to see if all of the bytes come from the same value.
2891 Value *V = ByteValues[0];
2892 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2893
2894 // Check to make sure that all of the bytes come from the same value.
2895 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2896 if (ByteValues[i] != V)
2897 return 0;
2898
2899 // If they do then *success* we can turn this into a bswap. Figure out what
2900 // bswap to make it into.
2901 Module *M = I.getParent()->getParent()->getParent();
2902 const char *FnName;
2903 if (I.getType() == Type::UShortTy)
2904 FnName = "llvm.bswap.i16";
2905 else if (I.getType() == Type::UIntTy)
2906 FnName = "llvm.bswap.i32";
2907 else if (I.getType() == Type::ULongTy)
2908 FnName = "llvm.bswap.i64";
2909 else
2910 assert(0 && "Unknown integer type!");
2911 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
2912
2913 return new CallInst(F, V);
2914}
2915
2916
Chris Lattner113f4f42002-06-25 16:13:24 +00002917Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002918 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002919 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002920
Chris Lattner81a7a232004-10-16 18:11:37 +00002921 if (isa<UndefValue>(Op1))
2922 return ReplaceInstUsesWith(I, // X | undef -> -1
2923 ConstantIntegral::getAllOnesValue(I.getType()));
2924
Chris Lattner5b2edb12006-02-12 08:02:11 +00002925 // or X, X = X
2926 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002927 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002928
Chris Lattner5b2edb12006-02-12 08:02:11 +00002929 // See if we can simplify any instructions used by the instruction whose sole
2930 // purpose is to compute bits we don't care about.
2931 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002932 if (!isa<PackedType>(I.getType()) &&
2933 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002934 KnownZero, KnownOne))
2935 return &I;
2936
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002937 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002938 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002939 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002940 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2941 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002942 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2943 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002944 InsertNewInstBefore(Or, I);
2945 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2946 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002947
Chris Lattnerd4252a72004-07-30 07:50:03 +00002948 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2949 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2950 std::string Op0Name = Op0->getName(); Op0->setName("");
2951 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2952 InsertNewInstBefore(Or, I);
2953 return BinaryOperator::createXor(Or,
2954 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002955 }
Chris Lattner183b3362004-04-09 19:05:30 +00002956
2957 // Try to fold constant and into select arguments.
2958 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002959 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002960 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002961 if (isa<PHINode>(Op0))
2962 if (Instruction *NV = FoldOpIntoPhi(I))
2963 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002964 }
2965
Chris Lattner330628a2006-01-06 17:59:59 +00002966 Value *A = 0, *B = 0;
2967 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002968
2969 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2970 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2971 return ReplaceInstUsesWith(I, Op1);
2972 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2973 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2974 return ReplaceInstUsesWith(I, Op0);
2975
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002976 // (A | B) | C and A | (B | C) -> bswap if possible.
2977 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2978 match(Op1, m_Or(m_Value(), m_Value()))) {
2979 if (Instruction *BSwap = MatchBSwap(I))
2980 return BSwap;
2981 }
2982
Chris Lattnerb62f5082005-05-09 04:58:36 +00002983 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2984 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002985 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002986 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2987 Op0->setName("");
2988 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2989 }
2990
2991 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2992 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002993 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002994 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2995 Op0->setName("");
2996 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2997 }
2998
Chris Lattner15212982005-09-18 03:42:07 +00002999 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003000 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003001 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3002
3003 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3004 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3005
3006
Chris Lattner01f56c62005-09-18 06:02:59 +00003007 // If we have: ((V + N) & C1) | (V & C2)
3008 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3009 // replace with V+N.
3010 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003011 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003012 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3013 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3014 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003015 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003016 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003017 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003018 return ReplaceInstUsesWith(I, A);
3019 }
3020 // Or commutes, try both ways.
3021 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3022 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3023 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003024 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003025 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003026 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003027 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003028 }
3029 }
3030 }
Chris Lattner812aab72003-08-12 19:11:07 +00003031
Chris Lattnerd4252a72004-07-30 07:50:03 +00003032 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3033 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003034 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003035 ConstantIntegral::getAllOnesValue(I.getType()));
3036 } else {
3037 A = 0;
3038 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003039 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003040 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3041 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003042 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003043 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003044
Misha Brukman9c003d82004-07-30 12:50:08 +00003045 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003046 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3047 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3048 I.getName()+".demorgan"), I);
3049 return BinaryOperator::createNot(And);
3050 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003051 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003052
Chris Lattner3ac7c262003-08-13 20:16:26 +00003053 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003054 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003055 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3056 return R;
3057
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003058 Value *LHSVal, *RHSVal;
3059 ConstantInt *LHSCst, *RHSCst;
3060 Instruction::BinaryOps LHSCC, RHSCC;
3061 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3062 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3063 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3064 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003065 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003066 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3067 // Ensure that the larger constant is on the RHS.
3068 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3069 SetCondInst *LHS = cast<SetCondInst>(Op0);
3070 if (cast<ConstantBool>(Cmp)->getValue()) {
3071 std::swap(LHS, RHS);
3072 std::swap(LHSCst, RHSCst);
3073 std::swap(LHSCC, RHSCC);
3074 }
3075
3076 // At this point, we know we have have two setcc instructions
3077 // comparing a value against two constants and or'ing the result
3078 // together. Because of the above check, we know that we only have
3079 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3080 // FoldSetCCLogical check above), that the two constants are not
3081 // equal.
3082 assert(LHSCst != RHSCst && "Compares not folded above?");
3083
3084 switch (LHSCC) {
3085 default: assert(0 && "Unknown integer condition code!");
3086 case Instruction::SetEQ:
3087 switch (RHSCC) {
3088 default: assert(0 && "Unknown integer condition code!");
3089 case Instruction::SetEQ:
3090 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3091 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3092 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3093 LHSVal->getName()+".off");
3094 InsertNewInstBefore(Add, I);
3095 const Type *UnsType = Add->getType()->getUnsignedVersion();
3096 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3097 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3098 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3099 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3100 }
3101 break; // (X == 13 | X == 15) -> no change
3102
Chris Lattner5c219462005-04-19 06:04:18 +00003103 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3104 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003105 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3106 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3107 return ReplaceInstUsesWith(I, RHS);
3108 }
3109 break;
3110 case Instruction::SetNE:
3111 switch (RHSCC) {
3112 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003113 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3114 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3115 return ReplaceInstUsesWith(I, LHS);
3116 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003117 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003118 return ReplaceInstUsesWith(I, ConstantBool::True);
3119 }
3120 break;
3121 case Instruction::SetLT:
3122 switch (RHSCC) {
3123 default: assert(0 && "Unknown integer condition code!");
3124 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3125 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003126 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3127 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003128 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3129 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3130 return ReplaceInstUsesWith(I, RHS);
3131 }
3132 break;
3133 case Instruction::SetGT:
3134 switch (RHSCC) {
3135 default: assert(0 && "Unknown integer condition code!");
3136 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3137 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3138 return ReplaceInstUsesWith(I, LHS);
3139 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3140 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3141 return ReplaceInstUsesWith(I, ConstantBool::True);
3142 }
3143 }
3144 }
3145 }
Chris Lattner3af10532006-05-05 06:39:07 +00003146
3147 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3148 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003149 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003150 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003151 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003152 // Only do this if the casts both really cause code to be generated.
3153 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3154 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003155 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3156 Op1C->getOperand(0),
3157 I.getName());
3158 InsertNewInstBefore(NewOp, I);
3159 return new CastInst(NewOp, I.getType());
3160 }
3161 }
3162
Chris Lattner15212982005-09-18 03:42:07 +00003163
Chris Lattner113f4f42002-06-25 16:13:24 +00003164 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003165}
3166
Chris Lattnerc2076352004-02-16 01:20:27 +00003167// XorSelf - Implements: X ^ X --> 0
3168struct XorSelf {
3169 Value *RHS;
3170 XorSelf(Value *rhs) : RHS(rhs) {}
3171 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3172 Instruction *apply(BinaryOperator &Xor) const {
3173 return &Xor;
3174 }
3175};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003176
3177
Chris Lattner113f4f42002-06-25 16:13:24 +00003178Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003179 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003180 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003181
Chris Lattner81a7a232004-10-16 18:11:37 +00003182 if (isa<UndefValue>(Op1))
3183 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3184
Chris Lattnerc2076352004-02-16 01:20:27 +00003185 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3186 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3187 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003188 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003189 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003190
3191 // See if we can simplify any instructions used by the instruction whose sole
3192 // purpose is to compute bits we don't care about.
3193 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003194 if (!isa<PackedType>(I.getType()) &&
3195 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003196 KnownZero, KnownOne))
3197 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003198
Chris Lattner97638592003-07-23 21:37:07 +00003199 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003200 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003201 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003202 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003203 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003204 return new SetCondInst(SCI->getInverseCondition(),
3205 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003206
Chris Lattner8f2f5982003-11-05 01:06:05 +00003207 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003208 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3209 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003210 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3211 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003212 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003213 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003214 }
Chris Lattner023a4832004-06-18 06:07:51 +00003215
3216 // ~(~X & Y) --> (X | ~Y)
3217 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3218 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3219 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3220 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003221 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003222 Op0I->getOperand(1)->getName()+".not");
3223 InsertNewInstBefore(NotY, I);
3224 return BinaryOperator::createOr(Op0NotVal, NotY);
3225 }
3226 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003227
Chris Lattner97638592003-07-23 21:37:07 +00003228 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003229 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003230 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003231 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003232 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3233 return BinaryOperator::createSub(
3234 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003235 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003236 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003237 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003238 } else if (Op0I->getOpcode() == Instruction::Or) {
3239 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3240 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3241 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3242 // Anything in both C1 and C2 is known to be zero, remove it from
3243 // NewRHS.
3244 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3245 NewRHS = ConstantExpr::getAnd(NewRHS,
3246 ConstantExpr::getNot(CommonBits));
3247 WorkList.push_back(Op0I);
3248 I.setOperand(0, Op0I->getOperand(0));
3249 I.setOperand(1, NewRHS);
3250 return &I;
3251 }
Chris Lattner97638592003-07-23 21:37:07 +00003252 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003253 }
Chris Lattner183b3362004-04-09 19:05:30 +00003254
3255 // Try to fold constant and into select arguments.
3256 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003257 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003258 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003259 if (isa<PHINode>(Op0))
3260 if (Instruction *NV = FoldOpIntoPhi(I))
3261 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003262 }
3263
Chris Lattnerbb74e222003-03-10 23:06:50 +00003264 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003265 if (X == Op1)
3266 return ReplaceInstUsesWith(I,
3267 ConstantIntegral::getAllOnesValue(I.getType()));
3268
Chris Lattnerbb74e222003-03-10 23:06:50 +00003269 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003270 if (X == Op0)
3271 return ReplaceInstUsesWith(I,
3272 ConstantIntegral::getAllOnesValue(I.getType()));
3273
Chris Lattnerdcd07922006-04-01 08:03:55 +00003274 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003275 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003276 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003277 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003278 I.swapOperands();
3279 std::swap(Op0, Op1);
3280 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003281 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003282 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003283 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003284 } else if (Op1I->getOpcode() == Instruction::Xor) {
3285 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3286 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3287 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3288 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003289 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3290 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3291 Op1I->swapOperands();
3292 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3293 I.swapOperands(); // Simplified below.
3294 std::swap(Op0, Op1);
3295 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003296 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003297
Chris Lattnerdcd07922006-04-01 08:03:55 +00003298 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003299 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003300 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003301 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003302 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003303 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3304 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003305 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003306 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003307 } else if (Op0I->getOpcode() == Instruction::Xor) {
3308 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3309 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3310 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3311 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003312 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3313 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3314 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003315 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3316 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003317 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3318 InsertNewInstBefore(N, I);
3319 return BinaryOperator::createAnd(N, Op1);
3320 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003321 }
3322
Chris Lattner3ac7c262003-08-13 20:16:26 +00003323 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3324 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3325 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3326 return R;
3327
Chris Lattner3af10532006-05-05 06:39:07 +00003328 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3329 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003330 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003331 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003332 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003333 // Only do this if the casts both really cause code to be generated.
3334 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3335 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003336 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3337 Op1C->getOperand(0),
3338 I.getName());
3339 InsertNewInstBefore(NewOp, I);
3340 return new CastInst(NewOp, I.getType());
3341 }
3342 }
3343
Chris Lattner113f4f42002-06-25 16:13:24 +00003344 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003345}
3346
Chris Lattner6862fbd2004-09-29 17:40:11 +00003347/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3348/// overflowed for this type.
3349static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3350 ConstantInt *In2) {
3351 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3352 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3353}
3354
3355static bool isPositive(ConstantInt *C) {
3356 return cast<ConstantSInt>(C)->getValue() >= 0;
3357}
3358
3359/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3360/// overflowed for this type.
3361static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3362 ConstantInt *In2) {
3363 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3364
3365 if (In1->getType()->isUnsigned())
3366 return cast<ConstantUInt>(Result)->getValue() <
3367 cast<ConstantUInt>(In1)->getValue();
3368 if (isPositive(In1) != isPositive(In2))
3369 return false;
3370 if (isPositive(In1))
3371 return cast<ConstantSInt>(Result)->getValue() <
3372 cast<ConstantSInt>(In1)->getValue();
3373 return cast<ConstantSInt>(Result)->getValue() >
3374 cast<ConstantSInt>(In1)->getValue();
3375}
3376
Chris Lattner0798af32005-01-13 20:14:25 +00003377/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3378/// code necessary to compute the offset from the base pointer (without adding
3379/// in the base pointer). Return the result as a signed integer of intptr size.
3380static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3381 TargetData &TD = IC.getTargetData();
3382 gep_type_iterator GTI = gep_type_begin(GEP);
3383 const Type *UIntPtrTy = TD.getIntPtrType();
3384 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3385 Value *Result = Constant::getNullValue(SIntPtrTy);
3386
3387 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003388 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003389
Chris Lattner0798af32005-01-13 20:14:25 +00003390 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3391 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003392 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003393 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3394 SIntPtrTy);
3395 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3396 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003397 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003398 Scale = ConstantExpr::getMul(OpC, Scale);
3399 if (Constant *RC = dyn_cast<Constant>(Result))
3400 Result = ConstantExpr::getAdd(RC, Scale);
3401 else {
3402 // Emit an add instruction.
3403 Result = IC.InsertNewInstBefore(
3404 BinaryOperator::createAdd(Result, Scale,
3405 GEP->getName()+".offs"), I);
3406 }
3407 }
3408 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003409 // Convert to correct type.
3410 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3411 Op->getName()+".c"), I);
3412 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003413 // We'll let instcombine(mul) convert this to a shl if possible.
3414 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3415 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003416
3417 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003418 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003419 GEP->getName()+".offs"), I);
3420 }
3421 }
3422 return Result;
3423}
3424
3425/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3426/// else. At this point we know that the GEP is on the LHS of the comparison.
3427Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3428 Instruction::BinaryOps Cond,
3429 Instruction &I) {
3430 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003431
3432 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3433 if (isa<PointerType>(CI->getOperand(0)->getType()))
3434 RHS = CI->getOperand(0);
3435
Chris Lattner0798af32005-01-13 20:14:25 +00003436 Value *PtrBase = GEPLHS->getOperand(0);
3437 if (PtrBase == RHS) {
3438 // As an optimization, we don't actually have to compute the actual value of
3439 // OFFSET if this is a seteq or setne comparison, just return whether each
3440 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003441 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3442 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003443 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3444 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003445 bool EmitIt = true;
3446 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3447 if (isa<UndefValue>(C)) // undef index -> undef.
3448 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3449 if (C->isNullValue())
3450 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003451 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3452 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003453 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003454 return ReplaceInstUsesWith(I, // No comparison is needed here.
3455 ConstantBool::get(Cond == Instruction::SetNE));
3456 }
3457
3458 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003459 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003460 new SetCondInst(Cond, GEPLHS->getOperand(i),
3461 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3462 if (InVal == 0)
3463 InVal = Comp;
3464 else {
3465 InVal = InsertNewInstBefore(InVal, I);
3466 InsertNewInstBefore(Comp, I);
3467 if (Cond == Instruction::SetNE) // True if any are unequal
3468 InVal = BinaryOperator::createOr(InVal, Comp);
3469 else // True if all are equal
3470 InVal = BinaryOperator::createAnd(InVal, Comp);
3471 }
3472 }
3473 }
3474
3475 if (InVal)
3476 return InVal;
3477 else
3478 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3479 ConstantBool::get(Cond == Instruction::SetEQ));
3480 }
Chris Lattner0798af32005-01-13 20:14:25 +00003481
3482 // Only lower this if the setcc is the only user of the GEP or if we expect
3483 // the result to fold to a constant!
3484 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3485 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3486 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3487 return new SetCondInst(Cond, Offset,
3488 Constant::getNullValue(Offset->getType()));
3489 }
3490 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003491 // If the base pointers are different, but the indices are the same, just
3492 // compare the base pointer.
3493 if (PtrBase != GEPRHS->getOperand(0)) {
3494 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003495 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003496 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003497 if (IndicesTheSame)
3498 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3499 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3500 IndicesTheSame = false;
3501 break;
3502 }
3503
3504 // If all indices are the same, just compare the base pointers.
3505 if (IndicesTheSame)
3506 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3507 GEPRHS->getOperand(0));
3508
3509 // Otherwise, the base pointers are different and the indices are
3510 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003511 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003512 }
Chris Lattner0798af32005-01-13 20:14:25 +00003513
Chris Lattner81e84172005-01-13 22:25:21 +00003514 // If one of the GEPs has all zero indices, recurse.
3515 bool AllZeros = true;
3516 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3517 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3518 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3519 AllZeros = false;
3520 break;
3521 }
3522 if (AllZeros)
3523 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3524 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003525
3526 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003527 AllZeros = true;
3528 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3529 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3530 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3531 AllZeros = false;
3532 break;
3533 }
3534 if (AllZeros)
3535 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3536
Chris Lattner4fa89822005-01-14 00:20:05 +00003537 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3538 // If the GEPs only differ by one index, compare it.
3539 unsigned NumDifferences = 0; // Keep track of # differences.
3540 unsigned DiffOperand = 0; // The operand that differs.
3541 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3542 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003543 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3544 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003545 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003546 NumDifferences = 2;
3547 break;
3548 } else {
3549 if (NumDifferences++) break;
3550 DiffOperand = i;
3551 }
3552 }
3553
3554 if (NumDifferences == 0) // SAME GEP?
3555 return ReplaceInstUsesWith(I, // No comparison is needed here.
3556 ConstantBool::get(Cond == Instruction::SetEQ));
3557 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003558 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3559 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003560
3561 // Convert the operands to signed values to make sure to perform a
3562 // signed comparison.
3563 const Type *NewTy = LHSV->getType()->getSignedVersion();
3564 if (LHSV->getType() != NewTy)
3565 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3566 LHSV->getName()), I);
3567 if (RHSV->getType() != NewTy)
3568 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3569 RHSV->getName()), I);
3570 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003571 }
3572 }
3573
Chris Lattner0798af32005-01-13 20:14:25 +00003574 // Only lower this if the setcc is the only user of the GEP or if we expect
3575 // the result to fold to a constant!
3576 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3577 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3578 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3579 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3580 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3581 return new SetCondInst(Cond, L, R);
3582 }
3583 }
3584 return 0;
3585}
3586
3587
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003588Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003589 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3591 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003592
3593 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003594 if (Op0 == Op1)
3595 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003596
Chris Lattner81a7a232004-10-16 18:11:37 +00003597 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3598 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3599
Chris Lattner15ff1e12004-11-14 07:33:16 +00003600 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3601 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003602 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3603 isa<ConstantPointerNull>(Op0)) &&
3604 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003605 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003606 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3607
3608 // setcc's with boolean values can always be turned into bitwise operations
3609 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003610 switch (I.getOpcode()) {
3611 default: assert(0 && "Invalid setcc instruction!");
3612 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003613 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003614 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003615 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003616 }
Chris Lattner4456da62004-08-11 00:50:51 +00003617 case Instruction::SetNE:
3618 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003619
Chris Lattner4456da62004-08-11 00:50:51 +00003620 case Instruction::SetGT:
3621 std::swap(Op0, Op1); // Change setgt -> setlt
3622 // FALL THROUGH
3623 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3624 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3625 InsertNewInstBefore(Not, I);
3626 return BinaryOperator::createAnd(Not, Op1);
3627 }
3628 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003629 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003630 // FALL THROUGH
3631 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3632 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3633 InsertNewInstBefore(Not, I);
3634 return BinaryOperator::createOr(Not, Op1);
3635 }
3636 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003637 }
3638
Chris Lattner2dd01742004-06-09 04:24:29 +00003639 // See if we are doing a comparison between a constant and an instruction that
3640 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003641 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003642 // Check to see if we are comparing against the minimum or maximum value...
3643 if (CI->isMinValue()) {
3644 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3645 return ReplaceInstUsesWith(I, ConstantBool::False);
3646 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3647 return ReplaceInstUsesWith(I, ConstantBool::True);
3648 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3649 return BinaryOperator::createSetEQ(Op0, Op1);
3650 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3651 return BinaryOperator::createSetNE(Op0, Op1);
3652
3653 } else if (CI->isMaxValue()) {
3654 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3655 return ReplaceInstUsesWith(I, ConstantBool::False);
3656 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3657 return ReplaceInstUsesWith(I, ConstantBool::True);
3658 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3659 return BinaryOperator::createSetEQ(Op0, Op1);
3660 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3661 return BinaryOperator::createSetNE(Op0, Op1);
3662
3663 // Comparing against a value really close to min or max?
3664 } else if (isMinValuePlusOne(CI)) {
3665 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3666 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3667 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3668 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3669
3670 } else if (isMaxValueMinusOne(CI)) {
3671 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3672 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3673 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3674 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3675 }
3676
3677 // If we still have a setle or setge instruction, turn it into the
3678 // appropriate setlt or setgt instruction. Since the border cases have
3679 // already been handled above, this requires little checking.
3680 //
3681 if (I.getOpcode() == Instruction::SetLE)
3682 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3683 if (I.getOpcode() == Instruction::SetGE)
3684 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3685
Chris Lattneree0f2802006-02-12 02:07:56 +00003686
3687 // See if we can fold the comparison based on bits known to be zero or one
3688 // in the input.
3689 uint64_t KnownZero, KnownOne;
3690 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3691 KnownZero, KnownOne, 0))
3692 return &I;
3693
3694 // Given the known and unknown bits, compute a range that the LHS could be
3695 // in.
3696 if (KnownOne | KnownZero) {
3697 if (Ty->isUnsigned()) { // Unsigned comparison.
3698 uint64_t Min, Max;
3699 uint64_t RHSVal = CI->getZExtValue();
3700 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3701 Min, Max);
3702 switch (I.getOpcode()) { // LE/GE have been folded already.
3703 default: assert(0 && "Unknown setcc opcode!");
3704 case Instruction::SetEQ:
3705 if (Max < RHSVal || Min > RHSVal)
3706 return ReplaceInstUsesWith(I, ConstantBool::False);
3707 break;
3708 case Instruction::SetNE:
3709 if (Max < RHSVal || Min > RHSVal)
3710 return ReplaceInstUsesWith(I, ConstantBool::True);
3711 break;
3712 case Instruction::SetLT:
3713 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3714 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3715 break;
3716 case Instruction::SetGT:
3717 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3718 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3719 break;
3720 }
3721 } else { // Signed comparison.
3722 int64_t Min, Max;
3723 int64_t RHSVal = CI->getSExtValue();
3724 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3725 Min, Max);
3726 switch (I.getOpcode()) { // LE/GE have been folded already.
3727 default: assert(0 && "Unknown setcc opcode!");
3728 case Instruction::SetEQ:
3729 if (Max < RHSVal || Min > RHSVal)
3730 return ReplaceInstUsesWith(I, ConstantBool::False);
3731 break;
3732 case Instruction::SetNE:
3733 if (Max < RHSVal || Min > RHSVal)
3734 return ReplaceInstUsesWith(I, ConstantBool::True);
3735 break;
3736 case Instruction::SetLT:
3737 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3738 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3739 break;
3740 case Instruction::SetGT:
3741 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3742 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3743 break;
3744 }
3745 }
3746 }
3747
3748
Chris Lattnere1e10e12004-05-25 06:32:08 +00003749 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003750 switch (LHSI->getOpcode()) {
3751 case Instruction::And:
3752 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3753 LHSI->getOperand(0)->hasOneUse()) {
3754 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3755 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3756 // happens a LOT in code produced by the C front-end, for bitfield
3757 // access.
3758 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003759 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3760
3761 // Check to see if there is a noop-cast between the shift and the and.
3762 if (!Shift) {
3763 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3764 if (CI->getOperand(0)->getType()->isIntegral() &&
3765 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3766 CI->getType()->getPrimitiveSizeInBits())
3767 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3768 }
3769
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003770 ConstantUInt *ShAmt;
3771 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003772 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3773 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003774
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003775 // We can fold this as long as we can't shift unknown bits
3776 // into the mask. This can only happen with signed shift
3777 // rights, as they sign-extend.
3778 if (ShAmt) {
3779 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003780 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003781 if (!CanFold) {
3782 // To test for the bad case of the signed shr, see if any
3783 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003784 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3785 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3786
3787 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003788 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003789 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3790 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003791 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3792 CanFold = true;
3793 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003794
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003795 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003796 Constant *NewCst;
3797 if (Shift->getOpcode() == Instruction::Shl)
3798 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3799 else
3800 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003801
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003802 // Check to see if we are shifting out any of the bits being
3803 // compared.
3804 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3805 // If we shifted bits out, the fold is not going to work out.
3806 // As a special case, check to see if this means that the
3807 // result is always true or false now.
3808 if (I.getOpcode() == Instruction::SetEQ)
3809 return ReplaceInstUsesWith(I, ConstantBool::False);
3810 if (I.getOpcode() == Instruction::SetNE)
3811 return ReplaceInstUsesWith(I, ConstantBool::True);
3812 } else {
3813 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003814 Constant *NewAndCST;
3815 if (Shift->getOpcode() == Instruction::Shl)
3816 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3817 else
3818 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3819 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003820 if (AndTy == Ty)
3821 LHSI->setOperand(0, Shift->getOperand(0));
3822 else {
3823 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3824 *Shift);
3825 LHSI->setOperand(0, NewCast);
3826 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003827 WorkList.push_back(Shift); // Shift is dead.
3828 AddUsesToWorkList(I);
3829 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003830 }
3831 }
Chris Lattner35167c32004-06-09 07:59:58 +00003832 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003833 }
3834 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003835
Chris Lattner272d5ca2004-09-28 18:22:15 +00003836 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3837 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3838 switch (I.getOpcode()) {
3839 default: break;
3840 case Instruction::SetEQ:
3841 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003842 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3843
3844 // Check that the shift amount is in range. If not, don't perform
3845 // undefined shifts. When the shift is visited it will be
3846 // simplified.
3847 if (ShAmt->getValue() >= TypeBits)
3848 break;
3849
Chris Lattner272d5ca2004-09-28 18:22:15 +00003850 // If we are comparing against bits always shifted out, the
3851 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003852 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003853 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3854 if (Comp != CI) {// Comparing against a bit that we know is zero.
3855 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3856 Constant *Cst = ConstantBool::get(IsSetNE);
3857 return ReplaceInstUsesWith(I, Cst);
3858 }
3859
3860 if (LHSI->hasOneUse()) {
3861 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003862 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003863 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3864
3865 Constant *Mask;
3866 if (CI->getType()->isUnsigned()) {
3867 Mask = ConstantUInt::get(CI->getType(), Val);
3868 } else if (ShAmtVal != 0) {
3869 Mask = ConstantSInt::get(CI->getType(), Val);
3870 } else {
3871 Mask = ConstantInt::getAllOnesValue(CI->getType());
3872 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003873
Chris Lattner272d5ca2004-09-28 18:22:15 +00003874 Instruction *AndI =
3875 BinaryOperator::createAnd(LHSI->getOperand(0),
3876 Mask, LHSI->getName()+".mask");
3877 Value *And = InsertNewInstBefore(AndI, I);
3878 return new SetCondInst(I.getOpcode(), And,
3879 ConstantExpr::getUShr(CI, ShAmt));
3880 }
3881 }
3882 }
3883 }
3884 break;
3885
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003886 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003887 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003888 switch (I.getOpcode()) {
3889 default: break;
3890 case Instruction::SetEQ:
3891 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003892
3893 // Check that the shift amount is in range. If not, don't perform
3894 // undefined shifts. When the shift is visited it will be
3895 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003896 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003897 if (ShAmt->getValue() >= TypeBits)
3898 break;
3899
Chris Lattner1023b872004-09-27 16:18:50 +00003900 // If we are comparing against bits always shifted out, the
3901 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003902 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003903 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003904
Chris Lattner1023b872004-09-27 16:18:50 +00003905 if (Comp != CI) {// Comparing against a bit that we know is zero.
3906 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3907 Constant *Cst = ConstantBool::get(IsSetNE);
3908 return ReplaceInstUsesWith(I, Cst);
3909 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003910
Chris Lattner1023b872004-09-27 16:18:50 +00003911 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003912 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003913
Chris Lattner1023b872004-09-27 16:18:50 +00003914 // Otherwise strength reduce the shift into an and.
3915 uint64_t Val = ~0ULL; // All ones.
3916 Val <<= ShAmtVal; // Shift over to the right spot.
3917
3918 Constant *Mask;
3919 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003920 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003921 Mask = ConstantUInt::get(CI->getType(), Val);
3922 } else {
3923 Mask = ConstantSInt::get(CI->getType(), Val);
3924 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003925
Chris Lattner1023b872004-09-27 16:18:50 +00003926 Instruction *AndI =
3927 BinaryOperator::createAnd(LHSI->getOperand(0),
3928 Mask, LHSI->getName()+".mask");
3929 Value *And = InsertNewInstBefore(AndI, I);
3930 return new SetCondInst(I.getOpcode(), And,
3931 ConstantExpr::getShl(CI, ShAmt));
3932 }
3933 break;
3934 }
3935 }
3936 }
3937 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003938
Chris Lattner6862fbd2004-09-29 17:40:11 +00003939 case Instruction::Div:
3940 // Fold: (div X, C1) op C2 -> range check
3941 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3942 // Fold this div into the comparison, producing a range check.
3943 // Determine, based on the divide type, what the range is being
3944 // checked. If there is an overflow on the low or high side, remember
3945 // it, otherwise compute the range [low, hi) bounding the new value.
3946 bool LoOverflow = false, HiOverflow = 0;
3947 ConstantInt *LoBound = 0, *HiBound = 0;
3948
3949 ConstantInt *Prod;
3950 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3951
Chris Lattnera92af962004-10-11 19:40:04 +00003952 Instruction::BinaryOps Opcode = I.getOpcode();
3953
Chris Lattner6862fbd2004-09-29 17:40:11 +00003954 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3955 } else if (LHSI->getType()->isUnsigned()) { // udiv
3956 LoBound = Prod;
3957 LoOverflow = ProdOV;
3958 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3959 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3960 if (CI->isNullValue()) { // (X / pos) op 0
3961 // Can't overflow.
3962 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3963 HiBound = DivRHS;
3964 } else if (isPositive(CI)) { // (X / pos) op pos
3965 LoBound = Prod;
3966 LoOverflow = ProdOV;
3967 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3968 } else { // (X / pos) op neg
3969 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3970 LoOverflow = AddWithOverflow(LoBound, Prod,
3971 cast<ConstantInt>(DivRHSH));
3972 HiBound = Prod;
3973 HiOverflow = ProdOV;
3974 }
3975 } else { // Divisor is < 0.
3976 if (CI->isNullValue()) { // (X / neg) op 0
3977 LoBound = AddOne(DivRHS);
3978 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003979 if (HiBound == DivRHS)
3980 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003981 } else if (isPositive(CI)) { // (X / neg) op pos
3982 HiOverflow = LoOverflow = ProdOV;
3983 if (!LoOverflow)
3984 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3985 HiBound = AddOne(Prod);
3986 } else { // (X / neg) op neg
3987 LoBound = Prod;
3988 LoOverflow = HiOverflow = ProdOV;
3989 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3990 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003991
Chris Lattnera92af962004-10-11 19:40:04 +00003992 // Dividing by a negate swaps the condition.
3993 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003994 }
3995
3996 if (LoBound) {
3997 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003998 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003999 default: assert(0 && "Unhandled setcc opcode!");
4000 case Instruction::SetEQ:
4001 if (LoOverflow && HiOverflow)
4002 return ReplaceInstUsesWith(I, ConstantBool::False);
4003 else if (HiOverflow)
4004 return new SetCondInst(Instruction::SetGE, X, LoBound);
4005 else if (LoOverflow)
4006 return new SetCondInst(Instruction::SetLT, X, HiBound);
4007 else
4008 return InsertRangeTest(X, LoBound, HiBound, true, I);
4009 case Instruction::SetNE:
4010 if (LoOverflow && HiOverflow)
4011 return ReplaceInstUsesWith(I, ConstantBool::True);
4012 else if (HiOverflow)
4013 return new SetCondInst(Instruction::SetLT, X, LoBound);
4014 else if (LoOverflow)
4015 return new SetCondInst(Instruction::SetGE, X, HiBound);
4016 else
4017 return InsertRangeTest(X, LoBound, HiBound, false, I);
4018 case Instruction::SetLT:
4019 if (LoOverflow)
4020 return ReplaceInstUsesWith(I, ConstantBool::False);
4021 return new SetCondInst(Instruction::SetLT, X, LoBound);
4022 case Instruction::SetGT:
4023 if (HiOverflow)
4024 return ReplaceInstUsesWith(I, ConstantBool::False);
4025 return new SetCondInst(Instruction::SetGE, X, HiBound);
4026 }
4027 }
4028 }
4029 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004030 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004031
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004032 // Simplify seteq and setne instructions...
4033 if (I.getOpcode() == Instruction::SetEQ ||
4034 I.getOpcode() == Instruction::SetNE) {
4035 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4036
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004037 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004038 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4040 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004041 case Instruction::Rem:
4042 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4043 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4044 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004045 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4046 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4047 if (isPowerOf2_64(V)) {
4048 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004049 const Type *UTy = BO->getType()->getUnsignedVersion();
4050 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4051 UTy, "tmp"), I);
4052 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4053 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4054 RHSCst, BO->getName()), I);
4055 return BinaryOperator::create(I.getOpcode(), NewRem,
4056 Constant::getNullValue(UTy));
4057 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004058 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004059 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004060
Chris Lattnerc992add2003-08-13 05:33:12 +00004061 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004062 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4063 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004064 if (BO->hasOneUse())
4065 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4066 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004067 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004068 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4069 // efficiently invertible, or if the add has just this one use.
4070 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004071
Chris Lattnerc992add2003-08-13 05:33:12 +00004072 if (Value *NegVal = dyn_castNegVal(BOp1))
4073 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4074 else if (Value *NegVal = dyn_castNegVal(BOp0))
4075 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004076 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004077 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4078 BO->setName("");
4079 InsertNewInstBefore(Neg, I);
4080 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4081 }
4082 }
4083 break;
4084 case Instruction::Xor:
4085 // For the xor case, we can xor two constants together, eliminating
4086 // the explicit xor.
4087 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4088 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004089 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004090
4091 // FALLTHROUGH
4092 case Instruction::Sub:
4093 // Replace (([sub|xor] A, B) != 0) with (A != B)
4094 if (CI->isNullValue())
4095 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4096 BO->getOperand(1));
4097 break;
4098
4099 case Instruction::Or:
4100 // If bits are being or'd in that are not present in the constant we
4101 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004102 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004103 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004104 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004105 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004106 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004107 break;
4108
4109 case Instruction::And:
4110 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004111 // If bits are being compared against that are and'd out, then the
4112 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004113 if (!ConstantExpr::getAnd(CI,
4114 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004115 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004116
Chris Lattner35167c32004-06-09 07:59:58 +00004117 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004118 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004119 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4120 Instruction::SetNE, Op0,
4121 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004122
Chris Lattnerc992add2003-08-13 05:33:12 +00004123 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4124 // to be a signed value as appropriate.
4125 if (isSignBit(BOC)) {
4126 Value *X = BO->getOperand(0);
4127 // If 'X' is not signed, insert a cast now...
4128 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004129 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004130 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004131 }
4132 return new SetCondInst(isSetNE ? Instruction::SetLT :
4133 Instruction::SetGE, X,
4134 Constant::getNullValue(X->getType()));
4135 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004136
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004137 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004138 if (CI->isNullValue() && isHighOnes(BOC)) {
4139 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004140 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004141
4142 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004143 if (NegX->getType()->isSigned()) {
4144 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4145 X = InsertCastBefore(X, DestTy, I);
4146 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004147 }
4148
4149 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004150 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004151 }
4152
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004153 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004154 default: break;
4155 }
4156 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004157 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004158 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004159 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4160 Value *CastOp = Cast->getOperand(0);
4161 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004162 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004163 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004164 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004165 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004166 "Source and destination signednesses should differ!");
4167 if (Cast->getType()->isSigned()) {
4168 // If this is a signed comparison, check for comparisons in the
4169 // vicinity of zero.
4170 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4171 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004172 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004173 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004174 else if (I.getOpcode() == Instruction::SetGT &&
4175 cast<ConstantSInt>(CI)->getValue() == -1)
4176 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004177 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004178 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004179 } else {
4180 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4181 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004182 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004183 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004184 return BinaryOperator::createSetGT(CastOp,
4185 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004186 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004187 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004188 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004189 return BinaryOperator::createSetLT(CastOp,
4190 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004191 }
4192 }
4193 }
Chris Lattnere967b342003-06-04 05:10:11 +00004194 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004195 }
4196
Chris Lattner77c32c32005-04-23 15:31:55 +00004197 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4198 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4199 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4200 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004201 case Instruction::GetElementPtr:
4202 if (RHSC->isNullValue()) {
4203 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4204 bool isAllZeros = true;
4205 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4206 if (!isa<Constant>(LHSI->getOperand(i)) ||
4207 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4208 isAllZeros = false;
4209 break;
4210 }
4211 if (isAllZeros)
4212 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4213 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4214 }
4215 break;
4216
Chris Lattner77c32c32005-04-23 15:31:55 +00004217 case Instruction::PHI:
4218 if (Instruction *NV = FoldOpIntoPhi(I))
4219 return NV;
4220 break;
4221 case Instruction::Select:
4222 // If either operand of the select is a constant, we can fold the
4223 // comparison into the select arms, which will cause one to be
4224 // constant folded and the select turned into a bitwise or.
4225 Value *Op1 = 0, *Op2 = 0;
4226 if (LHSI->hasOneUse()) {
4227 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4228 // Fold the known value into the constant operand.
4229 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4230 // Insert a new SetCC of the other select operand.
4231 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4232 LHSI->getOperand(2), RHSC,
4233 I.getName()), I);
4234 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4235 // Fold the known value into the constant operand.
4236 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4237 // Insert a new SetCC of the other select operand.
4238 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4239 LHSI->getOperand(1), RHSC,
4240 I.getName()), I);
4241 }
4242 }
Jeff Cohen82639852005-04-23 21:38:35 +00004243
Chris Lattner77c32c32005-04-23 15:31:55 +00004244 if (Op1)
4245 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4246 break;
4247 }
4248 }
4249
Chris Lattner0798af32005-01-13 20:14:25 +00004250 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4251 if (User *GEP = dyn_castGetElementPtr(Op0))
4252 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4253 return NI;
4254 if (User *GEP = dyn_castGetElementPtr(Op1))
4255 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4256 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4257 return NI;
4258
Chris Lattner16930792003-11-03 04:25:02 +00004259 // Test to see if the operands of the setcc are casted versions of other
4260 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004261 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4262 Value *CastOp0 = CI->getOperand(0);
4263 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00004264 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00004265 (I.getOpcode() == Instruction::SetEQ ||
4266 I.getOpcode() == Instruction::SetNE)) {
4267 // We keep moving the cast from the left operand over to the right
4268 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004269 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004270
Chris Lattner16930792003-11-03 04:25:02 +00004271 // If operand #1 is a cast instruction, see if we can eliminate it as
4272 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004273 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4274 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004275 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004276 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004277
Chris Lattner16930792003-11-03 04:25:02 +00004278 // If Op1 is a constant, we can fold the cast into the constant.
4279 if (Op1->getType() != Op0->getType())
4280 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4281 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4282 } else {
4283 // Otherwise, cast the RHS right before the setcc
4284 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4285 InsertNewInstBefore(cast<Instruction>(Op1), I);
4286 }
4287 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4288 }
4289
Chris Lattner6444c372003-11-03 05:17:03 +00004290 // Handle the special case of: setcc (cast bool to X), <cst>
4291 // This comes up when you have code like
4292 // int X = A < B;
4293 // if (X) ...
4294 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004295 // with a constant or another cast from the same type.
4296 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4297 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4298 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004299 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004300
4301 if (I.getOpcode() == Instruction::SetNE ||
4302 I.getOpcode() == Instruction::SetEQ) {
4303 Value *A, *B;
4304 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4305 (A == Op1 || B == Op1)) {
4306 // (A^B) == A -> B == 0
4307 Value *OtherVal = A == Op1 ? B : A;
4308 return BinaryOperator::create(I.getOpcode(), OtherVal,
4309 Constant::getNullValue(A->getType()));
4310 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4311 (A == Op0 || B == Op0)) {
4312 // A == (A^B) -> B == 0
4313 Value *OtherVal = A == Op0 ? B : A;
4314 return BinaryOperator::create(I.getOpcode(), OtherVal,
4315 Constant::getNullValue(A->getType()));
4316 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4317 // (A-B) == A -> B == 0
4318 return BinaryOperator::create(I.getOpcode(), B,
4319 Constant::getNullValue(B->getType()));
4320 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4321 // A == (A-B) -> B == 0
4322 return BinaryOperator::create(I.getOpcode(), B,
4323 Constant::getNullValue(B->getType()));
4324 }
4325 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004326 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004327}
4328
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004329// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4330// We only handle extending casts so far.
4331//
4332Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4333 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4334 const Type *SrcTy = LHSCIOp->getType();
4335 const Type *DestTy = SCI.getOperand(0)->getType();
4336 Value *RHSCIOp;
4337
4338 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004339 return 0;
4340
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004341 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4342 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4343 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4344
4345 // Is this a sign or zero extension?
4346 bool isSignSrc = SrcTy->isSigned();
4347 bool isSignDest = DestTy->isSigned();
4348
4349 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4350 // Not an extension from the same type?
4351 RHSCIOp = CI->getOperand(0);
4352 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4353 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4354 // Compute the constant that would happen if we truncated to SrcTy then
4355 // reextended to DestTy.
4356 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4357
4358 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4359 RHSCIOp = Res;
4360 } else {
4361 // If the value cannot be represented in the shorter type, we cannot emit
4362 // a simple comparison.
4363 if (SCI.getOpcode() == Instruction::SetEQ)
4364 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4365 if (SCI.getOpcode() == Instruction::SetNE)
4366 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4367
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004368 // Evaluate the comparison for LT.
4369 Value *Result;
4370 if (DestTy->isSigned()) {
4371 // We're performing a signed comparison.
4372 if (isSignSrc) {
4373 // Signed extend and signed comparison.
4374 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4375 Result = ConstantBool::False;
4376 else
4377 Result = ConstantBool::True; // X < (large) --> true
4378 } else {
4379 // Unsigned extend and signed comparison.
4380 if (cast<ConstantSInt>(CI)->getValue() < 0)
4381 Result = ConstantBool::False;
4382 else
4383 Result = ConstantBool::True;
4384 }
4385 } else {
4386 // We're performing an unsigned comparison.
4387 if (!isSignSrc) {
4388 // Unsigned extend & compare -> always true.
4389 Result = ConstantBool::True;
4390 } else {
4391 // We're performing an unsigned comp with a sign extended value.
4392 // This is true if the input is >= 0. [aka >s -1]
4393 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4394 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4395 NegOne, SCI.getName()), SCI);
4396 }
Reid Spencer279fa252004-11-28 21:31:15 +00004397 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004398
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004399 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004400 if (SCI.getOpcode() == Instruction::SetLT) {
4401 return ReplaceInstUsesWith(SCI, Result);
4402 } else {
4403 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4404 if (Constant *CI = dyn_cast<Constant>(Result))
4405 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4406 else
4407 return BinaryOperator::createNot(Result);
4408 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004409 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004410 } else {
4411 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004412 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004413
Chris Lattner252a8452005-06-16 03:00:08 +00004414 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004415 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4416}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004417
Chris Lattnere8d6c602003-03-10 19:16:08 +00004418Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004419 assert(I.getOperand(1)->getType() == Type::UByteTy);
4420 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004421 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004422
4423 // shl X, 0 == X and shr X, 0 == X
4424 // shl 0, X == 0 and shr 0, X == 0
4425 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004426 Op0 == Constant::getNullValue(Op0->getType()))
4427 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004428
Chris Lattner81a7a232004-10-16 18:11:37 +00004429 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4430 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004431 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004432 else // undef << X -> 0 AND undef >>u X -> 0
4433 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4434 }
4435 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004436 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004437 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4438 else
4439 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4440 }
4441
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004442 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4443 if (!isLeftShift)
4444 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4445 if (CSI->isAllOnesValue())
4446 return ReplaceInstUsesWith(I, CSI);
4447
Chris Lattner183b3362004-04-09 19:05:30 +00004448 // Try to fold constant and into select arguments.
4449 if (isa<Constant>(Op0))
4450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004452 return R;
4453
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004454 // See if we can turn a signed shr into an unsigned shr.
4455 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004456 if (MaskedValueIsZero(Op0,
4457 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004458 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4459 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4460 I.getName()), I);
4461 return new CastInst(V, I.getType());
4462 }
4463 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004464
Chris Lattner14553932006-01-06 07:12:35 +00004465 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4466 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4467 return Res;
4468 return 0;
4469}
4470
4471Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4472 ShiftInst &I) {
4473 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004474 bool isSignedShift = Op0->getType()->isSigned();
4475 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004476
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004477 // See if we can simplify any instructions used by the instruction whose sole
4478 // purpose is to compute bits we don't care about.
4479 uint64_t KnownZero, KnownOne;
4480 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4481 KnownZero, KnownOne))
4482 return &I;
4483
Chris Lattner14553932006-01-06 07:12:35 +00004484 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4485 // of a signed value.
4486 //
4487 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4488 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004489 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004490 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4491 else {
4492 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4493 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004494 }
Chris Lattner14553932006-01-06 07:12:35 +00004495 }
4496
4497 // ((X*C1) << C2) == (X * (C1 << C2))
4498 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4499 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4500 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4501 return BinaryOperator::createMul(BO->getOperand(0),
4502 ConstantExpr::getShl(BOOp, Op1));
4503
4504 // Try to fold constant and into select arguments.
4505 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4507 return R;
4508 if (isa<PHINode>(Op0))
4509 if (Instruction *NV = FoldOpIntoPhi(I))
4510 return NV;
4511
4512 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004513 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4514 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4515 Value *V1, *V2;
4516 ConstantInt *CC;
4517 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004518 default: break;
4519 case Instruction::Add:
4520 case Instruction::And:
4521 case Instruction::Or:
4522 case Instruction::Xor:
4523 // These operators commute.
4524 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004525 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4526 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004527 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004528 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004529 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004530 Op0BO->getName());
4531 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004532 Instruction *X =
4533 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4534 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004535 InsertNewInstBefore(X, I); // (X + (Y << C))
4536 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004537 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004538 return BinaryOperator::createAnd(X, C2);
4539 }
Chris Lattner14553932006-01-06 07:12:35 +00004540
Chris Lattner797dee72005-09-18 06:30:59 +00004541 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4542 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4543 match(Op0BO->getOperand(1),
4544 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004545 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004546 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004547 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004548 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004549 Op0BO->getName());
4550 InsertNewInstBefore(YS, I); // (Y << C)
4551 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004552 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004553 V1->getName()+".mask");
4554 InsertNewInstBefore(XM, I); // X & (CC << C)
4555
4556 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4557 }
Chris Lattner14553932006-01-06 07:12:35 +00004558
Chris Lattner797dee72005-09-18 06:30:59 +00004559 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004560 case Instruction::Sub:
4561 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004562 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4563 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004564 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004565 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004566 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004567 Op0BO->getName());
4568 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004569 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004570 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004571 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004572 InsertNewInstBefore(X, I); // (X + (Y << C))
4573 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004574 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004575 return BinaryOperator::createAnd(X, C2);
4576 }
Chris Lattner14553932006-01-06 07:12:35 +00004577
Chris Lattner1df0e982006-05-31 21:14:00 +00004578 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004579 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4580 match(Op0BO->getOperand(0),
4581 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004582 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004583 cast<BinaryOperator>(Op0BO->getOperand(0))
4584 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004585 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004586 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004587 Op0BO->getName());
4588 InsertNewInstBefore(YS, I); // (Y << C)
4589 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004590 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004591 V1->getName()+".mask");
4592 InsertNewInstBefore(XM, I); // X & (CC << C)
4593
Chris Lattner1df0e982006-05-31 21:14:00 +00004594 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004595 }
Chris Lattner14553932006-01-06 07:12:35 +00004596
Chris Lattner27cb9db2005-09-18 05:12:10 +00004597 break;
Chris Lattner14553932006-01-06 07:12:35 +00004598 }
4599
4600
4601 // If the operand is an bitwise operator with a constant RHS, and the
4602 // shift is the only use, we can pull it out of the shift.
4603 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4604 bool isValid = true; // Valid only for And, Or, Xor
4605 bool highBitSet = false; // Transform if high bit of constant set?
4606
4607 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004608 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004609 case Instruction::Add:
4610 isValid = isLeftShift;
4611 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004612 case Instruction::Or:
4613 case Instruction::Xor:
4614 highBitSet = false;
4615 break;
4616 case Instruction::And:
4617 highBitSet = true;
4618 break;
Chris Lattner14553932006-01-06 07:12:35 +00004619 }
4620
4621 // If this is a signed shift right, and the high bit is modified
4622 // by the logical operation, do not perform the transformation.
4623 // The highBitSet boolean indicates the value of the high bit of
4624 // the constant which would cause it to be modified for this
4625 // operation.
4626 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004627 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004628 uint64_t Val = Op0C->getRawValue();
4629 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4630 }
4631
4632 if (isValid) {
4633 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4634
4635 Instruction *NewShift =
4636 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4637 Op0BO->getName());
4638 Op0BO->setName("");
4639 InsertNewInstBefore(NewShift, I);
4640
4641 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4642 NewRHS);
4643 }
4644 }
4645 }
4646 }
4647
Chris Lattnereb372a02006-01-06 07:52:12 +00004648 // Find out if this is a shift of a shift by a constant.
4649 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004650 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004651 ShiftOp = Op0SI;
4652 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4653 // If this is a noop-integer case of a shift instruction, use the shift.
4654 if (CI->getOperand(0)->getType()->isInteger() &&
4655 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4656 CI->getType()->getPrimitiveSizeInBits() &&
4657 isa<ShiftInst>(CI->getOperand(0))) {
4658 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4659 }
4660 }
4661
4662 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4663 // Find the operands and properties of the input shift. Note that the
4664 // signedness of the input shift may differ from the current shift if there
4665 // is a noop cast between the two.
4666 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4667 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004668 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004669
4670 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4671
4672 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4673 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4674
4675 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4676 if (isLeftShift == isShiftOfLeftShift) {
4677 // Do not fold these shifts if the first one is signed and the second one
4678 // is unsigned and this is a right shift. Further, don't do any folding
4679 // on them.
4680 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4681 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004682
Chris Lattnereb372a02006-01-06 07:52:12 +00004683 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4684 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4685 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004686
Chris Lattnereb372a02006-01-06 07:52:12 +00004687 Value *Op = ShiftOp->getOperand(0);
4688 if (isShiftOfSignedShift != isSignedShift)
4689 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4690 return new ShiftInst(I.getOpcode(), Op,
4691 ConstantUInt::get(Type::UByteTy, Amt));
4692 }
4693
4694 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4695 // signed types, we can only support the (A >> c1) << c2 configuration,
4696 // because it can not turn an arbitrary bit of A into a sign bit.
4697 if (isUnsignedShift || isLeftShift) {
4698 // Calculate bitmask for what gets shifted off the edge.
4699 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4700 if (isLeftShift)
4701 C = ConstantExpr::getShl(C, ShiftAmt1C);
4702 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004703 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004704
4705 Value *Op = ShiftOp->getOperand(0);
4706 if (isShiftOfSignedShift != isSignedShift)
4707 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4708
4709 Instruction *Mask =
4710 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4711 InsertNewInstBefore(Mask, I);
4712
4713 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004714 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004715 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004716 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004717 return new ShiftInst(I.getOpcode(), Mask,
4718 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004719 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4720 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4721 // Make sure to emit an unsigned shift right, not a signed one.
4722 Mask = InsertNewInstBefore(new CastInst(Mask,
4723 Mask->getType()->getUnsignedVersion(),
4724 Op->getName()), I);
4725 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004726 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004727 InsertNewInstBefore(Mask, I);
4728 return new CastInst(Mask, I.getType());
4729 } else {
4730 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4731 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4732 }
4733 } else {
4734 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4735 Op = InsertNewInstBefore(new CastInst(Mask,
4736 I.getType()->getSignedVersion(),
4737 Mask->getName()), I);
4738 Instruction *Shift =
4739 new ShiftInst(ShiftOp->getOpcode(), Op,
4740 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4741 InsertNewInstBefore(Shift, I);
4742
4743 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4744 C = ConstantExpr::getShl(C, Op1);
4745 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4746 InsertNewInstBefore(Mask, I);
4747 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004748 }
4749 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004750 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004751 // this case, C1 == C2 and C1 is 8, 16, or 32.
4752 if (ShiftAmt1 == ShiftAmt2) {
4753 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004754 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004755 case 8 : SExtType = Type::SByteTy; break;
4756 case 16: SExtType = Type::ShortTy; break;
4757 case 32: SExtType = Type::IntTy; break;
4758 }
4759
4760 if (SExtType) {
4761 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4762 SExtType, "sext");
4763 InsertNewInstBefore(NewTrunc, I);
4764 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004765 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004766 }
Chris Lattner86102b82005-01-01 16:22:27 +00004767 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004768 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004769 return 0;
4770}
4771
Chris Lattner48a44f72002-05-02 17:06:02 +00004772
Chris Lattner8f663e82005-10-29 04:36:15 +00004773/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4774/// expression. If so, decompose it, returning some value X, such that Val is
4775/// X*Scale+Offset.
4776///
4777static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4778 unsigned &Offset) {
4779 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4780 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4781 Offset = CI->getValue();
4782 Scale = 1;
4783 return ConstantUInt::get(Type::UIntTy, 0);
4784 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4785 if (I->getNumOperands() == 2) {
4786 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4787 if (I->getOpcode() == Instruction::Shl) {
4788 // This is a value scaled by '1 << the shift amt'.
4789 Scale = 1U << CUI->getValue();
4790 Offset = 0;
4791 return I->getOperand(0);
4792 } else if (I->getOpcode() == Instruction::Mul) {
4793 // This value is scaled by 'CUI'.
4794 Scale = CUI->getValue();
4795 Offset = 0;
4796 return I->getOperand(0);
4797 } else if (I->getOpcode() == Instruction::Add) {
4798 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4799 // divisible by C2.
4800 unsigned SubScale;
4801 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4802 Offset);
4803 Offset += CUI->getValue();
4804 if (SubScale > 1 && (Offset % SubScale == 0)) {
4805 Scale = SubScale;
4806 return SubVal;
4807 }
4808 }
4809 }
4810 }
4811 }
4812
4813 // Otherwise, we can't look past this.
4814 Scale = 1;
4815 Offset = 0;
4816 return Val;
4817}
4818
4819
Chris Lattner216be912005-10-24 06:03:58 +00004820/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4821/// try to eliminate the cast by moving the type information into the alloc.
4822Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4823 AllocationInst &AI) {
4824 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004825 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004826
Chris Lattnerac87beb2005-10-24 06:22:12 +00004827 // Remove any uses of AI that are dead.
4828 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4829 std::vector<Instruction*> DeadUsers;
4830 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4831 Instruction *User = cast<Instruction>(*UI++);
4832 if (isInstructionTriviallyDead(User)) {
4833 while (UI != E && *UI == User)
4834 ++UI; // If this instruction uses AI more than once, don't break UI.
4835
4836 // Add operands to the worklist.
4837 AddUsesToWorkList(*User);
4838 ++NumDeadInst;
4839 DEBUG(std::cerr << "IC: DCE: " << *User);
4840
4841 User->eraseFromParent();
4842 removeFromWorkList(User);
4843 }
4844 }
4845
Chris Lattner216be912005-10-24 06:03:58 +00004846 // Get the type really allocated and the type casted to.
4847 const Type *AllocElTy = AI.getAllocatedType();
4848 const Type *CastElTy = PTy->getElementType();
4849 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004850
4851 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4852 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4853 if (CastElTyAlign < AllocElTyAlign) return 0;
4854
Chris Lattner46705b22005-10-24 06:35:18 +00004855 // If the allocation has multiple uses, only promote it if we are strictly
4856 // increasing the alignment of the resultant allocation. If we keep it the
4857 // same, we open the door to infinite loops of various kinds.
4858 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4859
Chris Lattner216be912005-10-24 06:03:58 +00004860 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4861 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004862 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004863
Chris Lattner8270c332005-10-29 03:19:53 +00004864 // See if we can satisfy the modulus by pulling a scale out of the array
4865 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004866 unsigned ArraySizeScale, ArrayOffset;
4867 Value *NumElements = // See if the array size is a decomposable linear expr.
4868 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4869
Chris Lattner8270c332005-10-29 03:19:53 +00004870 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4871 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004872 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4873 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004874
Chris Lattner8270c332005-10-29 03:19:53 +00004875 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4876 Value *Amt = 0;
4877 if (Scale == 1) {
4878 Amt = NumElements;
4879 } else {
4880 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4881 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4882 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4883 else if (Scale != 1) {
4884 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4885 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004886 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004887 }
4888
Chris Lattner8f663e82005-10-29 04:36:15 +00004889 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4890 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4891 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4892 Amt = InsertNewInstBefore(Tmp, AI);
4893 }
4894
Chris Lattner216be912005-10-24 06:03:58 +00004895 std::string Name = AI.getName(); AI.setName("");
4896 AllocationInst *New;
4897 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004898 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004899 else
Nate Begeman848622f2005-11-05 09:21:28 +00004900 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004901 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004902
4903 // If the allocation has multiple uses, insert a cast and change all things
4904 // that used it to use the new cast. This will also hack on CI, but it will
4905 // die soon.
4906 if (!AI.hasOneUse()) {
4907 AddUsesToWorkList(AI);
4908 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4909 InsertNewInstBefore(NewCast, AI);
4910 AI.replaceAllUsesWith(NewCast);
4911 }
Chris Lattner216be912005-10-24 06:03:58 +00004912 return ReplaceInstUsesWith(CI, New);
4913}
4914
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004915/// CanEvaluateInDifferentType - Return true if we can take the specified value
4916/// and return it without inserting any new casts. This is used by code that
4917/// tries to decide whether promoting or shrinking integer operations to wider
4918/// or smaller types will allow us to eliminate a truncate or extend.
4919static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4920 int &NumCastsRemoved) {
4921 if (isa<Constant>(V)) return true;
4922
4923 Instruction *I = dyn_cast<Instruction>(V);
4924 if (!I || !I->hasOneUse()) return false;
4925
4926 switch (I->getOpcode()) {
4927 case Instruction::And:
4928 case Instruction::Or:
4929 case Instruction::Xor:
4930 // These operators can all arbitrarily be extended or truncated.
4931 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4932 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4933 case Instruction::Cast:
4934 // If this is a cast from the destination type, we can trivially eliminate
4935 // it, and this will remove a cast overall.
4936 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00004937 // If the first operand is itself a cast, and is eliminable, do not count
4938 // this as an eliminable cast. We would prefer to eliminate those two
4939 // casts first.
4940 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
4941 return true;
4942
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004943 ++NumCastsRemoved;
4944 return true;
4945 }
4946 // TODO: Can handle more cases here.
4947 break;
4948 }
4949
4950 return false;
4951}
4952
4953/// EvaluateInDifferentType - Given an expression that
4954/// CanEvaluateInDifferentType returns true for, actually insert the code to
4955/// evaluate the expression.
4956Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
4957 if (Constant *C = dyn_cast<Constant>(V))
4958 return ConstantExpr::getCast(C, Ty);
4959
4960 // Otherwise, it must be an instruction.
4961 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00004962 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004963 switch (I->getOpcode()) {
4964 case Instruction::And:
4965 case Instruction::Or:
4966 case Instruction::Xor: {
4967 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
4968 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
4969 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
4970 LHS, RHS, I->getName());
4971 break;
4972 }
4973 case Instruction::Cast:
4974 // If this is a cast from the destination type, return the input.
4975 if (I->getOperand(0)->getType() == Ty)
4976 return I->getOperand(0);
4977
4978 // TODO: Can handle more cases here.
4979 assert(0 && "Unreachable!");
4980 break;
4981 }
4982
4983 return InsertNewInstBefore(Res, *I);
4984}
4985
Chris Lattner216be912005-10-24 06:03:58 +00004986
Chris Lattner48a44f72002-05-02 17:06:02 +00004987// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004988//
Chris Lattner113f4f42002-06-25 16:13:24 +00004989Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004990 Value *Src = CI.getOperand(0);
4991
Chris Lattner48a44f72002-05-02 17:06:02 +00004992 // If the user is casting a value to the same type, eliminate this cast
4993 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004994 if (CI.getType() == Src->getType())
4995 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004996
Chris Lattner81a7a232004-10-16 18:11:37 +00004997 if (isa<UndefValue>(Src)) // cast undef -> undef
4998 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4999
Chris Lattner48a44f72002-05-02 17:06:02 +00005000 // If casting the result of another cast instruction, try to eliminate this
5001 // one!
5002 //
Chris Lattner86102b82005-01-01 16:22:27 +00005003 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5004 Value *A = CSrc->getOperand(0);
5005 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5006 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005007 // This instruction now refers directly to the cast's src operand. This
5008 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005009 CI.setOperand(0, CSrc->getOperand(0));
5010 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005011 }
5012
Chris Lattner650b6da2002-08-02 20:00:25 +00005013 // If this is an A->B->A cast, and we are dealing with integral types, try
5014 // to convert this into a logical 'and' instruction.
5015 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005016 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005017 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005018 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005019 CSrc->getType()->getPrimitiveSizeInBits() <
5020 CI.getType()->getPrimitiveSizeInBits()&&
5021 A->getType()->getPrimitiveSizeInBits() ==
5022 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005023 assert(CSrc->getType() != Type::ULongTy &&
5024 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005025 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005026 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5027 AndValue);
5028 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5029 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5030 if (And->getType() != CI.getType()) {
5031 And->setName(CSrc->getName()+".mask");
5032 InsertNewInstBefore(And, CI);
5033 And = new CastInst(And, CI.getType());
5034 }
5035 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005036 }
5037 }
Chris Lattner2590e512006-02-07 06:56:34 +00005038
Chris Lattner03841652004-05-25 04:29:21 +00005039 // If this is a cast to bool, turn it into the appropriate setne instruction.
5040 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005041 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005042 Constant::getNullValue(CI.getOperand(0)->getType()));
5043
Chris Lattner2590e512006-02-07 06:56:34 +00005044 // See if we can simplify any instructions used by the LHS whose sole
5045 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005046 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5047 uint64_t KnownZero, KnownOne;
5048 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5049 KnownZero, KnownOne))
5050 return &CI;
5051 }
Chris Lattner2590e512006-02-07 06:56:34 +00005052
Chris Lattnerd0d51602003-06-21 23:12:02 +00005053 // If casting the result of a getelementptr instruction with no offset, turn
5054 // this into a cast of the original pointer!
5055 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005056 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005057 bool AllZeroOperands = true;
5058 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5059 if (!isa<Constant>(GEP->getOperand(i)) ||
5060 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5061 AllZeroOperands = false;
5062 break;
5063 }
5064 if (AllZeroOperands) {
5065 CI.setOperand(0, GEP->getOperand(0));
5066 return &CI;
5067 }
5068 }
5069
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005070 // If we are casting a malloc or alloca to a pointer to a type of the same
5071 // size, rewrite the allocation instruction to allocate the "right" type.
5072 //
5073 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005074 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5075 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005076
Chris Lattner86102b82005-01-01 16:22:27 +00005077 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5078 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5079 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005080 if (isa<PHINode>(Src))
5081 if (Instruction *NV = FoldOpIntoPhi(CI))
5082 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005083
5084 // If the source and destination are pointers, and this cast is equivalent to
5085 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5086 // This can enhance SROA and other transforms that want type-safe pointers.
5087 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5088 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5089 const Type *DstTy = DstPTy->getElementType();
5090 const Type *SrcTy = SrcPTy->getElementType();
5091
5092 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5093 unsigned NumZeros = 0;
5094 while (SrcTy != DstTy &&
5095 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
5096 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5097 ++NumZeros;
5098 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005099
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005100 // If we found a path from the src to dest, create the getelementptr now.
5101 if (SrcTy == DstTy) {
5102 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5103 return new GetElementPtrInst(Src, Idxs);
5104 }
5105 }
5106
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005107 // If the source value is an instruction with only this use, we can attempt to
5108 // propagate the cast into the instruction. Also, only handle integral types
5109 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005110 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005111 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005112 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005113
5114 int NumCastsRemoved = 0;
5115 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5116 // If this cast is a truncate, evaluting in a different type always
5117 // eliminates the cast, so it is always a win. If this is a noop-cast
5118 // this just removes a noop cast which isn't pointful, but simplifies
5119 // the code. If this is a zero-extension, we need to do an AND to
5120 // maintain the clear top-part of the computation, so we require that
5121 // the input have eliminated at least one cast. If this is a sign
5122 // extension, we insert two new casts (to do the extension) so we
5123 // require that two casts have been eliminated.
5124 bool DoXForm;
5125 switch (getCastType(Src->getType(), CI.getType())) {
5126 default: assert(0 && "Unknown cast type!");
5127 case Noop:
5128 case Truncate:
5129 DoXForm = true;
5130 break;
5131 case Zeroext:
5132 DoXForm = NumCastsRemoved >= 1;
5133 break;
5134 case Signext:
5135 DoXForm = NumCastsRemoved >= 2;
5136 break;
5137 }
5138
5139 if (DoXForm) {
5140 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5141 assert(Res->getType() == CI.getType());
5142 switch (getCastType(Src->getType(), CI.getType())) {
5143 default: assert(0 && "Unknown cast type!");
5144 case Noop:
5145 case Truncate:
5146 // Just replace this cast with the result.
5147 return ReplaceInstUsesWith(CI, Res);
5148 case Zeroext: {
5149 // We need to emit an AND to clear the high bits.
5150 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5151 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5152 assert(SrcBitSize < DestBitSize && "Not a zext?");
5153 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5154 C = ConstantExpr::getCast(C, CI.getType());
5155 return BinaryOperator::createAnd(Res, C);
5156 }
5157 case Signext:
5158 // We need to emit a cast to truncate, then a cast to sext.
5159 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5160 CI.getType());
5161 }
5162 }
5163 }
5164
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005165 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005166 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5167 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005168
5169 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5170 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5171
5172 switch (SrcI->getOpcode()) {
5173 case Instruction::Add:
5174 case Instruction::Mul:
5175 case Instruction::And:
5176 case Instruction::Or:
5177 case Instruction::Xor:
5178 // If we are discarding information, or just changing the sign, rewrite.
5179 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5180 // Don't insert two casts if they cannot be eliminated. We allow two
5181 // casts to be inserted if the sizes are the same. This could only be
5182 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005183 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5184 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005185 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5186 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5187 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5188 ->getOpcode(), Op0c, Op1c);
5189 }
5190 }
Chris Lattner72086162005-05-06 02:07:39 +00005191
5192 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5193 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5194 Op1 == ConstantBool::True &&
5195 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5196 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5197 return BinaryOperator::createXor(New,
5198 ConstantInt::get(CI.getType(), 1));
5199 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005200 break;
5201 case Instruction::Shl:
5202 // Allow changing the sign of the source operand. Do not allow changing
5203 // the size of the shift, UNLESS the shift amount is a constant. We
5204 // mush not change variable sized shifts to a smaller size, because it
5205 // is undefined to shift more bits out than exist in the value.
5206 if (DestBitSize == SrcBitSize ||
5207 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5208 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5209 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5210 }
5211 break;
Chris Lattner87380412005-05-06 04:18:52 +00005212 case Instruction::Shr:
5213 // If this is a signed shr, and if all bits shifted in are about to be
5214 // truncated off, turn it into an unsigned shr to allow greater
5215 // simplifications.
5216 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5217 isa<ConstantInt>(Op1)) {
5218 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5219 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5220 // Convert to unsigned.
5221 Value *N1 = InsertOperandCastBefore(Op0,
5222 Op0->getType()->getUnsignedVersion(), &CI);
5223 // Insert the new shift, which is now unsigned.
5224 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5225 Op1, Src->getName()), CI);
5226 return new CastInst(N1, CI.getType());
5227 }
5228 }
5229 break;
5230
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005231 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005232 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005233 // We if we are just checking for a seteq of a single bit and casting it
5234 // to an integer. If so, shift the bit to the appropriate place then
5235 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005236 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005237 uint64_t Op1CV = Op1C->getZExtValue();
5238 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5239 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5240 // cast (X == 1) to int --> X iff X has only the low bit set.
5241 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5242 // cast (X != 0) to int --> X iff X has only the low bit set.
5243 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5244 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5245 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5246 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5247 // If Op1C some other power of two, convert:
5248 uint64_t KnownZero, KnownOne;
5249 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5250 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5251
5252 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5253 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5254 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5255 // (X&4) == 2 --> false
5256 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005257 Constant *Res = ConstantBool::get(isSetNE);
5258 Res = ConstantExpr::getCast(Res, CI.getType());
5259 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005260 }
5261
5262 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5263 Value *In = Op0;
5264 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005265 // Perform an unsigned shr by shiftamt. Convert input to
5266 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005267 if (In->getType()->isSigned())
5268 In = InsertNewInstBefore(new CastInst(In,
5269 In->getType()->getUnsignedVersion(), In->getName()),CI);
5270 // Insert the shift to put the result in the low bit.
5271 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005272 ConstantInt::get(Type::UByteTy, ShiftAmt),
5273 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005274 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005275
5276 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5277 Constant *One = ConstantInt::get(In->getType(), 1);
5278 In = BinaryOperator::createXor(In, One, "tmp");
5279 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005280 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005281
5282 if (CI.getType() == In->getType())
5283 return ReplaceInstUsesWith(CI, In);
5284 else
5285 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005286 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005287 }
5288 }
5289 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005290 }
5291 }
Chris Lattner99155be2006-05-25 23:24:33 +00005292
5293 if (SrcI->hasOneUse()) {
5294 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5295 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5296 // because the inputs are known to be a vector. Check to see if this is
5297 // a cast to a vector with the same # elts.
5298 if (isa<PackedType>(CI.getType()) &&
5299 cast<PackedType>(CI.getType())->getNumElements() ==
5300 SVI->getType()->getNumElements()) {
5301 CastInst *Tmp;
5302 // If either of the operands is a cast from CI.getType(), then
5303 // evaluating the shuffle in the casted destination's type will allow
5304 // us to eliminate at least one cast.
5305 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5306 Tmp->getOperand(0)->getType() == CI.getType()) ||
5307 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005308 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005309 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5310 CI.getType(), &CI);
5311 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5312 CI.getType(), &CI);
5313 // Return a new shuffle vector. Use the same element ID's, as we
5314 // know the vector types match #elts.
5315 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5316 }
5317 }
5318 }
5319 }
5320 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005321
Chris Lattner260ab202002-04-18 17:39:14 +00005322 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005323}
5324
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005325/// GetSelectFoldableOperands - We want to turn code that looks like this:
5326/// %C = or %A, %B
5327/// %D = select %cond, %C, %A
5328/// into:
5329/// %C = select %cond, %B, 0
5330/// %D = or %A, %C
5331///
5332/// Assuming that the specified instruction is an operand to the select, return
5333/// a bitmask indicating which operands of this instruction are foldable if they
5334/// equal the other incoming value of the select.
5335///
5336static unsigned GetSelectFoldableOperands(Instruction *I) {
5337 switch (I->getOpcode()) {
5338 case Instruction::Add:
5339 case Instruction::Mul:
5340 case Instruction::And:
5341 case Instruction::Or:
5342 case Instruction::Xor:
5343 return 3; // Can fold through either operand.
5344 case Instruction::Sub: // Can only fold on the amount subtracted.
5345 case Instruction::Shl: // Can only fold on the shift amount.
5346 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005347 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005348 default:
5349 return 0; // Cannot fold
5350 }
5351}
5352
5353/// GetSelectFoldableConstant - For the same transformation as the previous
5354/// function, return the identity constant that goes into the select.
5355static Constant *GetSelectFoldableConstant(Instruction *I) {
5356 switch (I->getOpcode()) {
5357 default: assert(0 && "This cannot happen!"); abort();
5358 case Instruction::Add:
5359 case Instruction::Sub:
5360 case Instruction::Or:
5361 case Instruction::Xor:
5362 return Constant::getNullValue(I->getType());
5363 case Instruction::Shl:
5364 case Instruction::Shr:
5365 return Constant::getNullValue(Type::UByteTy);
5366 case Instruction::And:
5367 return ConstantInt::getAllOnesValue(I->getType());
5368 case Instruction::Mul:
5369 return ConstantInt::get(I->getType(), 1);
5370 }
5371}
5372
Chris Lattner411336f2005-01-19 21:50:18 +00005373/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5374/// have the same opcode and only one use each. Try to simplify this.
5375Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5376 Instruction *FI) {
5377 if (TI->getNumOperands() == 1) {
5378 // If this is a non-volatile load or a cast from the same type,
5379 // merge.
5380 if (TI->getOpcode() == Instruction::Cast) {
5381 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5382 return 0;
5383 } else {
5384 return 0; // unknown unary op.
5385 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005386
Chris Lattner411336f2005-01-19 21:50:18 +00005387 // Fold this by inserting a select from the input values.
5388 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5389 FI->getOperand(0), SI.getName()+".v");
5390 InsertNewInstBefore(NewSI, SI);
5391 return new CastInst(NewSI, TI->getType());
5392 }
5393
5394 // Only handle binary operators here.
5395 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5396 return 0;
5397
5398 // Figure out if the operations have any operands in common.
5399 Value *MatchOp, *OtherOpT, *OtherOpF;
5400 bool MatchIsOpZero;
5401 if (TI->getOperand(0) == FI->getOperand(0)) {
5402 MatchOp = TI->getOperand(0);
5403 OtherOpT = TI->getOperand(1);
5404 OtherOpF = FI->getOperand(1);
5405 MatchIsOpZero = true;
5406 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5407 MatchOp = TI->getOperand(1);
5408 OtherOpT = TI->getOperand(0);
5409 OtherOpF = FI->getOperand(0);
5410 MatchIsOpZero = false;
5411 } else if (!TI->isCommutative()) {
5412 return 0;
5413 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5414 MatchOp = TI->getOperand(0);
5415 OtherOpT = TI->getOperand(1);
5416 OtherOpF = FI->getOperand(0);
5417 MatchIsOpZero = true;
5418 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5419 MatchOp = TI->getOperand(1);
5420 OtherOpT = TI->getOperand(0);
5421 OtherOpF = FI->getOperand(1);
5422 MatchIsOpZero = true;
5423 } else {
5424 return 0;
5425 }
5426
5427 // If we reach here, they do have operations in common.
5428 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5429 OtherOpF, SI.getName()+".v");
5430 InsertNewInstBefore(NewSI, SI);
5431
5432 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5433 if (MatchIsOpZero)
5434 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5435 else
5436 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5437 } else {
5438 if (MatchIsOpZero)
5439 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5440 else
5441 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5442 }
5443}
5444
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005445Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005446 Value *CondVal = SI.getCondition();
5447 Value *TrueVal = SI.getTrueValue();
5448 Value *FalseVal = SI.getFalseValue();
5449
5450 // select true, X, Y -> X
5451 // select false, X, Y -> Y
5452 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005453 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005454 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005455 else {
5456 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005457 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005458 }
Chris Lattner533bc492004-03-30 19:37:13 +00005459
5460 // select C, X, X -> X
5461 if (TrueVal == FalseVal)
5462 return ReplaceInstUsesWith(SI, TrueVal);
5463
Chris Lattner81a7a232004-10-16 18:11:37 +00005464 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5465 return ReplaceInstUsesWith(SI, FalseVal);
5466 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5467 return ReplaceInstUsesWith(SI, TrueVal);
5468 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5469 if (isa<Constant>(TrueVal))
5470 return ReplaceInstUsesWith(SI, TrueVal);
5471 else
5472 return ReplaceInstUsesWith(SI, FalseVal);
5473 }
5474
Chris Lattner1c631e82004-04-08 04:43:23 +00005475 if (SI.getType() == Type::BoolTy)
5476 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5477 if (C == ConstantBool::True) {
5478 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005479 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005480 } else {
5481 // Change: A = select B, false, C --> A = and !B, C
5482 Value *NotCond =
5483 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5484 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005485 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005486 }
5487 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5488 if (C == ConstantBool::False) {
5489 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005490 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005491 } else {
5492 // Change: A = select B, C, true --> A = or !B, C
5493 Value *NotCond =
5494 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5495 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005496 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005497 }
5498 }
5499
Chris Lattner183b3362004-04-09 19:05:30 +00005500 // Selecting between two integer constants?
5501 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5502 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5503 // select C, 1, 0 -> cast C to int
5504 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5505 return new CastInst(CondVal, SI.getType());
5506 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5507 // select C, 0, 1 -> cast !C to int
5508 Value *NotCond =
5509 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005510 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005511 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005512 }
Chris Lattner35167c32004-06-09 07:59:58 +00005513
5514 // If one of the constants is zero (we know they can't both be) and we
5515 // have a setcc instruction with zero, and we have an 'and' with the
5516 // non-constant value, eliminate this whole mess. This corresponds to
5517 // cases like this: ((X & 27) ? 27 : 0)
5518 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5519 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5520 if ((IC->getOpcode() == Instruction::SetEQ ||
5521 IC->getOpcode() == Instruction::SetNE) &&
5522 isa<ConstantInt>(IC->getOperand(1)) &&
5523 cast<Constant>(IC->getOperand(1))->isNullValue())
5524 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5525 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005526 isa<ConstantInt>(ICA->getOperand(1)) &&
5527 (ICA->getOperand(1) == TrueValC ||
5528 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005529 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5530 // Okay, now we know that everything is set up, we just don't
5531 // know whether we have a setne or seteq and whether the true or
5532 // false val is the zero.
5533 bool ShouldNotVal = !TrueValC->isNullValue();
5534 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5535 Value *V = ICA;
5536 if (ShouldNotVal)
5537 V = InsertNewInstBefore(BinaryOperator::create(
5538 Instruction::Xor, V, ICA->getOperand(1)), SI);
5539 return ReplaceInstUsesWith(SI, V);
5540 }
Chris Lattner533bc492004-03-30 19:37:13 +00005541 }
Chris Lattner623fba12004-04-10 22:21:27 +00005542
5543 // See if we are selecting two values based on a comparison of the two values.
5544 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5545 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5546 // Transform (X == Y) ? X : Y -> Y
5547 if (SCI->getOpcode() == Instruction::SetEQ)
5548 return ReplaceInstUsesWith(SI, FalseVal);
5549 // Transform (X != Y) ? X : Y -> X
5550 if (SCI->getOpcode() == Instruction::SetNE)
5551 return ReplaceInstUsesWith(SI, TrueVal);
5552 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5553
5554 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5555 // Transform (X == Y) ? Y : X -> X
5556 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005557 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005558 // Transform (X != Y) ? Y : X -> Y
5559 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005560 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005561 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5562 }
5563 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005564
Chris Lattnera04c9042005-01-13 22:52:24 +00005565 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5566 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5567 if (TI->hasOneUse() && FI->hasOneUse()) {
5568 bool isInverse = false;
5569 Instruction *AddOp = 0, *SubOp = 0;
5570
Chris Lattner411336f2005-01-19 21:50:18 +00005571 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5572 if (TI->getOpcode() == FI->getOpcode())
5573 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5574 return IV;
5575
5576 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5577 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005578 if (TI->getOpcode() == Instruction::Sub &&
5579 FI->getOpcode() == Instruction::Add) {
5580 AddOp = FI; SubOp = TI;
5581 } else if (FI->getOpcode() == Instruction::Sub &&
5582 TI->getOpcode() == Instruction::Add) {
5583 AddOp = TI; SubOp = FI;
5584 }
5585
5586 if (AddOp) {
5587 Value *OtherAddOp = 0;
5588 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5589 OtherAddOp = AddOp->getOperand(1);
5590 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5591 OtherAddOp = AddOp->getOperand(0);
5592 }
5593
5594 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005595 // So at this point we know we have (Y -> OtherAddOp):
5596 // select C, (add X, Y), (sub X, Z)
5597 Value *NegVal; // Compute -Z
5598 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5599 NegVal = ConstantExpr::getNeg(C);
5600 } else {
5601 NegVal = InsertNewInstBefore(
5602 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005603 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005604
5605 Value *NewTrueOp = OtherAddOp;
5606 Value *NewFalseOp = NegVal;
5607 if (AddOp != TI)
5608 std::swap(NewTrueOp, NewFalseOp);
5609 Instruction *NewSel =
5610 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5611
5612 NewSel = InsertNewInstBefore(NewSel, SI);
5613 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005614 }
5615 }
5616 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005617
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005618 // See if we can fold the select into one of our operands.
5619 if (SI.getType()->isInteger()) {
5620 // See the comment above GetSelectFoldableOperands for a description of the
5621 // transformation we are doing here.
5622 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5623 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5624 !isa<Constant>(FalseVal))
5625 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5626 unsigned OpToFold = 0;
5627 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5628 OpToFold = 1;
5629 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5630 OpToFold = 2;
5631 }
5632
5633 if (OpToFold) {
5634 Constant *C = GetSelectFoldableConstant(TVI);
5635 std::string Name = TVI->getName(); TVI->setName("");
5636 Instruction *NewSel =
5637 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5638 Name);
5639 InsertNewInstBefore(NewSel, SI);
5640 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5641 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5642 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5643 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5644 else {
5645 assert(0 && "Unknown instruction!!");
5646 }
5647 }
5648 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005649
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005650 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5651 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5652 !isa<Constant>(TrueVal))
5653 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5654 unsigned OpToFold = 0;
5655 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5656 OpToFold = 1;
5657 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5658 OpToFold = 2;
5659 }
5660
5661 if (OpToFold) {
5662 Constant *C = GetSelectFoldableConstant(FVI);
5663 std::string Name = FVI->getName(); FVI->setName("");
5664 Instruction *NewSel =
5665 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5666 Name);
5667 InsertNewInstBefore(NewSel, SI);
5668 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5669 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5670 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5671 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5672 else {
5673 assert(0 && "Unknown instruction!!");
5674 }
5675 }
5676 }
5677 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005678
5679 if (BinaryOperator::isNot(CondVal)) {
5680 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5681 SI.setOperand(1, FalseVal);
5682 SI.setOperand(2, TrueVal);
5683 return &SI;
5684 }
5685
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005686 return 0;
5687}
5688
Chris Lattner82f2ef22006-03-06 20:18:44 +00005689/// GetKnownAlignment - If the specified pointer has an alignment that we can
5690/// determine, return it, otherwise return 0.
5691static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5692 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5693 unsigned Align = GV->getAlignment();
5694 if (Align == 0 && TD)
5695 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5696 return Align;
5697 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5698 unsigned Align = AI->getAlignment();
5699 if (Align == 0 && TD) {
5700 if (isa<AllocaInst>(AI))
5701 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5702 else if (isa<MallocInst>(AI)) {
5703 // Malloc returns maximally aligned memory.
5704 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5705 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5706 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5707 }
5708 }
5709 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005710 } else if (isa<CastInst>(V) ||
5711 (isa<ConstantExpr>(V) &&
5712 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5713 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005714 if (isa<PointerType>(CI->getOperand(0)->getType()))
5715 return GetKnownAlignment(CI->getOperand(0), TD);
5716 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005717 } else if (isa<GetElementPtrInst>(V) ||
5718 (isa<ConstantExpr>(V) &&
5719 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5720 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005721 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5722 if (BaseAlignment == 0) return 0;
5723
5724 // If all indexes are zero, it is just the alignment of the base pointer.
5725 bool AllZeroOperands = true;
5726 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5727 if (!isa<Constant>(GEPI->getOperand(i)) ||
5728 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5729 AllZeroOperands = false;
5730 break;
5731 }
5732 if (AllZeroOperands)
5733 return BaseAlignment;
5734
5735 // Otherwise, if the base alignment is >= the alignment we expect for the
5736 // base pointer type, then we know that the resultant pointer is aligned at
5737 // least as much as its type requires.
5738 if (!TD) return 0;
5739
5740 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5741 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005742 <= BaseAlignment) {
5743 const Type *GEPTy = GEPI->getType();
5744 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5745 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005746 return 0;
5747 }
5748 return 0;
5749}
5750
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005751
Chris Lattnerc66b2232006-01-13 20:11:04 +00005752/// visitCallInst - CallInst simplification. This mostly only handles folding
5753/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5754/// the heavy lifting.
5755///
Chris Lattner970c33a2003-06-19 17:00:31 +00005756Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005757 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5758 if (!II) return visitCallSite(&CI);
5759
Chris Lattner51ea1272004-02-28 05:22:00 +00005760 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5761 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005762 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005763 bool Changed = false;
5764
5765 // memmove/cpy/set of zero bytes is a noop.
5766 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5767 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5768
Chris Lattner00648e12004-10-12 04:52:52 +00005769 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5770 if (CI->getRawValue() == 1) {
5771 // Replace the instruction with just byte operations. We would
5772 // transform other cases to loads/stores, but we don't know if
5773 // alignment is sufficient.
5774 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005775 }
5776
Chris Lattner00648e12004-10-12 04:52:52 +00005777 // If we have a memmove and the source operation is a constant global,
5778 // then the source and dest pointers can't alias, so we can change this
5779 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005780 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005781 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5782 if (GVSrc->isConstant()) {
5783 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005784 const char *Name;
5785 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5786 Type::UIntTy)
5787 Name = "llvm.memcpy.i32";
5788 else
5789 Name = "llvm.memcpy.i64";
5790 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005791 CI.getCalledFunction()->getFunctionType());
5792 CI.setOperand(0, MemCpy);
5793 Changed = true;
5794 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005795 }
Chris Lattner00648e12004-10-12 04:52:52 +00005796
Chris Lattner82f2ef22006-03-06 20:18:44 +00005797 // If we can determine a pointer alignment that is bigger than currently
5798 // set, update the alignment.
5799 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5800 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5801 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5802 unsigned Align = std::min(Alignment1, Alignment2);
5803 if (MI->getAlignment()->getRawValue() < Align) {
5804 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5805 Changed = true;
5806 }
5807 } else if (isa<MemSetInst>(MI)) {
5808 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5809 if (MI->getAlignment()->getRawValue() < Alignment) {
5810 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5811 Changed = true;
5812 }
5813 }
5814
Chris Lattnerc66b2232006-01-13 20:11:04 +00005815 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005816 } else {
5817 switch (II->getIntrinsicID()) {
5818 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005819 case Intrinsic::ppc_altivec_lvx:
5820 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00005821 case Intrinsic::x86_sse_loadu_ps:
5822 case Intrinsic::x86_sse2_loadu_pd:
5823 case Intrinsic::x86_sse2_loadu_dq:
5824 // Turn PPC lvx -> load if the pointer is known aligned.
5825 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005826 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005827 Value *Ptr = InsertCastBefore(II->getOperand(1),
5828 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005829 return new LoadInst(Ptr);
5830 }
5831 break;
5832 case Intrinsic::ppc_altivec_stvx:
5833 case Intrinsic::ppc_altivec_stvxl:
5834 // Turn stvx -> store if the pointer is known aligned.
5835 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005836 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5837 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005838 return new StoreInst(II->getOperand(1), Ptr);
5839 }
5840 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00005841 case Intrinsic::x86_sse_storeu_ps:
5842 case Intrinsic::x86_sse2_storeu_pd:
5843 case Intrinsic::x86_sse2_storeu_dq:
5844 case Intrinsic::x86_sse2_storel_dq:
5845 // Turn X86 storeu -> store if the pointer is known aligned.
5846 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5847 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5848 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5849 return new StoreInst(II->getOperand(2), Ptr);
5850 }
5851 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005852 case Intrinsic::ppc_altivec_vperm:
5853 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5854 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5855 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5856
5857 // Check that all of the elements are integer constants or undefs.
5858 bool AllEltsOk = true;
5859 for (unsigned i = 0; i != 16; ++i) {
5860 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5861 !isa<UndefValue>(Mask->getOperand(i))) {
5862 AllEltsOk = false;
5863 break;
5864 }
5865 }
5866
5867 if (AllEltsOk) {
5868 // Cast the input vectors to byte vectors.
5869 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5870 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5871 Value *Result = UndefValue::get(Op0->getType());
5872
5873 // Only extract each element once.
5874 Value *ExtractedElts[32];
5875 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5876
5877 for (unsigned i = 0; i != 16; ++i) {
5878 if (isa<UndefValue>(Mask->getOperand(i)))
5879 continue;
5880 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5881 Idx &= 31; // Match the hardware behavior.
5882
5883 if (ExtractedElts[Idx] == 0) {
5884 Instruction *Elt =
5885 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5886 ConstantUInt::get(Type::UIntTy, Idx&15),
5887 "tmp");
5888 InsertNewInstBefore(Elt, CI);
5889 ExtractedElts[Idx] = Elt;
5890 }
5891
5892 // Insert this value into the result vector.
5893 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5894 ConstantUInt::get(Type::UIntTy, i),
5895 "tmp");
5896 InsertNewInstBefore(cast<Instruction>(Result), CI);
5897 }
5898 return new CastInst(Result, CI.getType());
5899 }
5900 }
5901 break;
5902
Chris Lattner503221f2006-01-13 21:28:09 +00005903 case Intrinsic::stackrestore: {
5904 // If the save is right next to the restore, remove the restore. This can
5905 // happen when variable allocas are DCE'd.
5906 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5907 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5908 BasicBlock::iterator BI = SS;
5909 if (&*++BI == II)
5910 return EraseInstFromFunction(CI);
5911 }
5912 }
5913
5914 // If the stack restore is in a return/unwind block and if there are no
5915 // allocas or calls between the restore and the return, nuke the restore.
5916 TerminatorInst *TI = II->getParent()->getTerminator();
5917 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5918 BasicBlock::iterator BI = II;
5919 bool CannotRemove = false;
5920 for (++BI; &*BI != TI; ++BI) {
5921 if (isa<AllocaInst>(BI) ||
5922 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5923 CannotRemove = true;
5924 break;
5925 }
5926 }
5927 if (!CannotRemove)
5928 return EraseInstFromFunction(CI);
5929 }
5930 break;
5931 }
5932 }
Chris Lattner00648e12004-10-12 04:52:52 +00005933 }
5934
Chris Lattnerc66b2232006-01-13 20:11:04 +00005935 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005936}
5937
5938// InvokeInst simplification
5939//
5940Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005941 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005942}
5943
Chris Lattneraec3d942003-10-07 22:32:43 +00005944// visitCallSite - Improvements for call and invoke instructions.
5945//
5946Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005947 bool Changed = false;
5948
5949 // If the callee is a constexpr cast of a function, attempt to move the cast
5950 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005951 if (transformConstExprCastCall(CS)) return 0;
5952
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005953 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005954
Chris Lattner61d9d812005-05-13 07:09:09 +00005955 if (Function *CalleeF = dyn_cast<Function>(Callee))
5956 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5957 Instruction *OldCall = CS.getInstruction();
5958 // If the call and callee calling conventions don't match, this call must
5959 // be unreachable, as the call is undefined.
5960 new StoreInst(ConstantBool::True,
5961 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5962 if (!OldCall->use_empty())
5963 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5964 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5965 return EraseInstFromFunction(*OldCall);
5966 return 0;
5967 }
5968
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005969 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5970 // This instruction is not reachable, just remove it. We insert a store to
5971 // undef so that we know that this code is not reachable, despite the fact
5972 // that we can't modify the CFG here.
5973 new StoreInst(ConstantBool::True,
5974 UndefValue::get(PointerType::get(Type::BoolTy)),
5975 CS.getInstruction());
5976
5977 if (!CS.getInstruction()->use_empty())
5978 CS.getInstruction()->
5979 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5980
5981 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5982 // Don't break the CFG, insert a dummy cond branch.
5983 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5984 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005985 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005986 return EraseInstFromFunction(*CS.getInstruction());
5987 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005988
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005989 const PointerType *PTy = cast<PointerType>(Callee->getType());
5990 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5991 if (FTy->isVarArg()) {
5992 // See if we can optimize any arguments passed through the varargs area of
5993 // the call.
5994 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5995 E = CS.arg_end(); I != E; ++I)
5996 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5997 // If this cast does not effect the value passed through the varargs
5998 // area, we can eliminate the use of the cast.
5999 Value *Op = CI->getOperand(0);
6000 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6001 *I = Op;
6002 Changed = true;
6003 }
6004 }
6005 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006006
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006007 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006008}
6009
Chris Lattner970c33a2003-06-19 17:00:31 +00006010// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6011// attempt to move the cast to the arguments of the call/invoke.
6012//
6013bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6014 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6015 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006016 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006017 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006018 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006019 Instruction *Caller = CS.getInstruction();
6020
6021 // Okay, this is a cast from a function to a different type. Unless doing so
6022 // would cause a type conversion of one of our arguments, change this call to
6023 // be a direct call with arguments casted to the appropriate types.
6024 //
6025 const FunctionType *FT = Callee->getFunctionType();
6026 const Type *OldRetTy = Caller->getType();
6027
Chris Lattner1f7942f2004-01-14 06:06:08 +00006028 // Check to see if we are changing the return type...
6029 if (OldRetTy != FT->getReturnType()) {
6030 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006031 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6032 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006033 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006034 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006035 return false; // Cannot transform this return value...
6036
6037 // If the callsite is an invoke instruction, and the return value is used by
6038 // a PHI node in a successor, we cannot change the return type of the call
6039 // because there is no place to put the cast instruction (without breaking
6040 // the critical edge). Bail out in this case.
6041 if (!Caller->use_empty())
6042 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6043 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6044 UI != E; ++UI)
6045 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6046 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006047 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006048 return false;
6049 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006050
6051 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6052 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006053
Chris Lattner970c33a2003-06-19 17:00:31 +00006054 CallSite::arg_iterator AI = CS.arg_begin();
6055 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6056 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006057 const Type *ActTy = (*AI)->getType();
6058 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6059 //Either we can cast directly, or we can upconvert the argument
6060 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6061 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6062 ParamTy->isSigned() == ActTy->isSigned() &&
6063 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6064 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6065 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006066 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006067 }
6068
6069 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6070 Callee->isExternal())
6071 return false; // Do not delete arguments unless we have a function body...
6072
6073 // Okay, we decided that this is a safe thing to do: go ahead and start
6074 // inserting cast instructions as necessary...
6075 std::vector<Value*> Args;
6076 Args.reserve(NumActualArgs);
6077
6078 AI = CS.arg_begin();
6079 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6080 const Type *ParamTy = FT->getParamType(i);
6081 if ((*AI)->getType() == ParamTy) {
6082 Args.push_back(*AI);
6083 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006084 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6085 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006086 }
6087 }
6088
6089 // If the function takes more arguments than the call was taking, add them
6090 // now...
6091 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6092 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6093
6094 // If we are removing arguments to the function, emit an obnoxious warning...
6095 if (FT->getNumParams() < NumActualArgs)
6096 if (!FT->isVarArg()) {
6097 std::cerr << "WARNING: While resolving call to function '"
6098 << Callee->getName() << "' arguments were dropped!\n";
6099 } else {
6100 // Add all of the arguments in their promoted form to the arg list...
6101 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6102 const Type *PTy = getPromotedType((*AI)->getType());
6103 if (PTy != (*AI)->getType()) {
6104 // Must promote to pass through va_arg area!
6105 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6106 InsertNewInstBefore(Cast, *Caller);
6107 Args.push_back(Cast);
6108 } else {
6109 Args.push_back(*AI);
6110 }
6111 }
6112 }
6113
6114 if (FT->getReturnType() == Type::VoidTy)
6115 Caller->setName(""); // Void type should not have a name...
6116
6117 Instruction *NC;
6118 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006119 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006120 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006121 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006122 } else {
6123 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006124 if (cast<CallInst>(Caller)->isTailCall())
6125 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006126 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006127 }
6128
6129 // Insert a cast of the return type as necessary...
6130 Value *NV = NC;
6131 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6132 if (NV->getType() != Type::VoidTy) {
6133 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006134
6135 // If this is an invoke instruction, we should insert it after the first
6136 // non-phi, instruction in the normal successor block.
6137 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6138 BasicBlock::iterator I = II->getNormalDest()->begin();
6139 while (isa<PHINode>(I)) ++I;
6140 InsertNewInstBefore(NC, *I);
6141 } else {
6142 // Otherwise, it's a call, just insert cast right after the call instr
6143 InsertNewInstBefore(NC, *Caller);
6144 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006145 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006146 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006147 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006148 }
6149 }
6150
6151 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6152 Caller->replaceAllUsesWith(NV);
6153 Caller->getParent()->getInstList().erase(Caller);
6154 removeFromWorkList(Caller);
6155 return true;
6156}
6157
6158
Chris Lattner7515cab2004-11-14 19:13:23 +00006159// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6160// operator and they all are only used by the PHI, PHI together their
6161// inputs, and do the operation once, to the result of the PHI.
6162Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6163 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6164
6165 // Scan the instruction, looking for input operations that can be folded away.
6166 // If all input operands to the phi are the same instruction (e.g. a cast from
6167 // the same type or "+42") we can pull the operation through the PHI, reducing
6168 // code size and simplifying code.
6169 Constant *ConstantOp = 0;
6170 const Type *CastSrcTy = 0;
6171 if (isa<CastInst>(FirstInst)) {
6172 CastSrcTy = FirstInst->getOperand(0)->getType();
6173 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6174 // Can fold binop or shift if the RHS is a constant.
6175 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6176 if (ConstantOp == 0) return 0;
6177 } else {
6178 return 0; // Cannot fold this operation.
6179 }
6180
6181 // Check to see if all arguments are the same operation.
6182 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6183 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6184 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6185 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6186 return 0;
6187 if (CastSrcTy) {
6188 if (I->getOperand(0)->getType() != CastSrcTy)
6189 return 0; // Cast operation must match.
6190 } else if (I->getOperand(1) != ConstantOp) {
6191 return 0;
6192 }
6193 }
6194
6195 // Okay, they are all the same operation. Create a new PHI node of the
6196 // correct type, and PHI together all of the LHS's of the instructions.
6197 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6198 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006199 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006200
6201 Value *InVal = FirstInst->getOperand(0);
6202 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006203
6204 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006205 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6206 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6207 if (NewInVal != InVal)
6208 InVal = 0;
6209 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6210 }
6211
6212 Value *PhiVal;
6213 if (InVal) {
6214 // The new PHI unions all of the same values together. This is really
6215 // common, so we handle it intelligently here for compile-time speed.
6216 PhiVal = InVal;
6217 delete NewPN;
6218 } else {
6219 InsertNewInstBefore(NewPN, PN);
6220 PhiVal = NewPN;
6221 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006222
Chris Lattner7515cab2004-11-14 19:13:23 +00006223 // Insert and return the new operation.
6224 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006225 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006226 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006227 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006228 else
6229 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006230 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006231}
Chris Lattner48a44f72002-05-02 17:06:02 +00006232
Chris Lattner71536432005-01-17 05:10:15 +00006233/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6234/// that is dead.
6235static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6236 if (PN->use_empty()) return true;
6237 if (!PN->hasOneUse()) return false;
6238
6239 // Remember this node, and if we find the cycle, return.
6240 if (!PotentiallyDeadPHIs.insert(PN).second)
6241 return true;
6242
6243 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6244 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006245
Chris Lattner71536432005-01-17 05:10:15 +00006246 return false;
6247}
6248
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006249// PHINode simplification
6250//
Chris Lattner113f4f42002-06-25 16:13:24 +00006251Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00006252 if (Value *V = PN.hasConstantValue())
6253 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00006254
6255 // If the only user of this instruction is a cast instruction, and all of the
6256 // incoming values are constants, change this PHI to merge together the casted
6257 // constants.
6258 if (PN.hasOneUse())
6259 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6260 if (CI->getType() != PN.getType()) { // noop casts will be folded
6261 bool AllConstant = true;
6262 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6263 if (!isa<Constant>(PN.getIncomingValue(i))) {
6264 AllConstant = false;
6265 break;
6266 }
6267 if (AllConstant) {
6268 // Make a new PHI with all casted values.
6269 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6270 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6271 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6272 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6273 PN.getIncomingBlock(i));
6274 }
6275
6276 // Update the cast instruction.
6277 CI->setOperand(0, New);
6278 WorkList.push_back(CI); // revisit the cast instruction to fold.
6279 WorkList.push_back(New); // Make sure to revisit the new Phi
6280 return &PN; // PN is now dead!
6281 }
6282 }
Chris Lattner7515cab2004-11-14 19:13:23 +00006283
6284 // If all PHI operands are the same operation, pull them through the PHI,
6285 // reducing code size.
6286 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6287 PN.getIncomingValue(0)->hasOneUse())
6288 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6289 return Result;
6290
Chris Lattner71536432005-01-17 05:10:15 +00006291 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6292 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6293 // PHI)... break the cycle.
6294 if (PN.hasOneUse())
6295 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6296 std::set<PHINode*> PotentiallyDeadPHIs;
6297 PotentiallyDeadPHIs.insert(&PN);
6298 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6299 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6300 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006301
Chris Lattner91daeb52003-12-19 05:58:40 +00006302 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006303}
6304
Chris Lattner69193f92004-04-05 01:30:19 +00006305static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6306 Instruction *InsertPoint,
6307 InstCombiner *IC) {
6308 unsigned PS = IC->getTargetData().getPointerSize();
6309 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006310 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6311 // We must insert a cast to ensure we sign-extend.
6312 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6313 V->getName()), *InsertPoint);
6314 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6315 *InsertPoint);
6316}
6317
Chris Lattner48a44f72002-05-02 17:06:02 +00006318
Chris Lattner113f4f42002-06-25 16:13:24 +00006319Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006320 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006321 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006322 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006323 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006324 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006325
Chris Lattner81a7a232004-10-16 18:11:37 +00006326 if (isa<UndefValue>(GEP.getOperand(0)))
6327 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6328
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006329 bool HasZeroPointerIndex = false;
6330 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6331 HasZeroPointerIndex = C->isNullValue();
6332
6333 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006334 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006335
Chris Lattner69193f92004-04-05 01:30:19 +00006336 // Eliminate unneeded casts for indices.
6337 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006338 gep_type_iterator GTI = gep_type_begin(GEP);
6339 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6340 if (isa<SequentialType>(*GTI)) {
6341 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6342 Value *Src = CI->getOperand(0);
6343 const Type *SrcTy = Src->getType();
6344 const Type *DestTy = CI->getType();
6345 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006346 if (SrcTy->getPrimitiveSizeInBits() ==
6347 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006348 // We can always eliminate a cast from ulong or long to the other.
6349 // We can always eliminate a cast from uint to int or the other on
6350 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006351 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006352 MadeChange = true;
6353 GEP.setOperand(i, Src);
6354 }
6355 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6356 SrcTy->getPrimitiveSize() == 4) {
6357 // We can always eliminate a cast from int to [u]long. We can
6358 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6359 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006360 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006361 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006362 MadeChange = true;
6363 GEP.setOperand(i, Src);
6364 }
Chris Lattner69193f92004-04-05 01:30:19 +00006365 }
6366 }
6367 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006368 // If we are using a wider index than needed for this platform, shrink it
6369 // to what we need. If the incoming value needs a cast instruction,
6370 // insert it. This explicit cast can make subsequent optimizations more
6371 // obvious.
6372 Value *Op = GEP.getOperand(i);
6373 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006374 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006375 GEP.setOperand(i, ConstantExpr::getCast(C,
6376 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006377 MadeChange = true;
6378 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006379 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6380 Op->getName()), GEP);
6381 GEP.setOperand(i, Op);
6382 MadeChange = true;
6383 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006384
6385 // If this is a constant idx, make sure to canonicalize it to be a signed
6386 // operand, otherwise CSE and other optimizations are pessimized.
6387 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6388 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6389 CUI->getType()->getSignedVersion()));
6390 MadeChange = true;
6391 }
Chris Lattner69193f92004-04-05 01:30:19 +00006392 }
6393 if (MadeChange) return &GEP;
6394
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006395 // Combine Indices - If the source pointer to this getelementptr instruction
6396 // is a getelementptr instruction, combine the indices of the two
6397 // getelementptr instructions into a single instruction.
6398 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006399 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006400 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006401 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006402
6403 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006404 // Note that if our source is a gep chain itself that we wait for that
6405 // chain to be resolved before we perform this transformation. This
6406 // avoids us creating a TON of code in some cases.
6407 //
6408 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6409 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6410 return 0; // Wait until our source is folded to completion.
6411
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006412 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006413
6414 // Find out whether the last index in the source GEP is a sequential idx.
6415 bool EndsWithSequential = false;
6416 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6417 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006418 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006419
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006420 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006421 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006422 // Replace: gep (gep %P, long B), long A, ...
6423 // With: T = long A+B; gep %P, T, ...
6424 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006425 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006426 if (SO1 == Constant::getNullValue(SO1->getType())) {
6427 Sum = GO1;
6428 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6429 Sum = SO1;
6430 } else {
6431 // If they aren't the same type, convert both to an integer of the
6432 // target's pointer size.
6433 if (SO1->getType() != GO1->getType()) {
6434 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6435 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6436 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6437 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6438 } else {
6439 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006440 if (SO1->getType()->getPrimitiveSize() == PS) {
6441 // Convert GO1 to SO1's type.
6442 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6443
6444 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6445 // Convert SO1 to GO1's type.
6446 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6447 } else {
6448 const Type *PT = TD->getIntPtrType();
6449 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6450 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6451 }
6452 }
6453 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006454 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6455 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6456 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006457 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6458 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006459 }
Chris Lattner69193f92004-04-05 01:30:19 +00006460 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006461
6462 // Recycle the GEP we already have if possible.
6463 if (SrcGEPOperands.size() == 2) {
6464 GEP.setOperand(0, SrcGEPOperands[0]);
6465 GEP.setOperand(1, Sum);
6466 return &GEP;
6467 } else {
6468 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6469 SrcGEPOperands.end()-1);
6470 Indices.push_back(Sum);
6471 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6472 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006473 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006474 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006475 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006476 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006477 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6478 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006479 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6480 }
6481
6482 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006483 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006484
Chris Lattner5f667a62004-05-07 22:09:22 +00006485 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006486 // GEP of global variable. If all of the indices for this GEP are
6487 // constants, we can promote this to a constexpr instead of an instruction.
6488
6489 // Scan for nonconstants...
6490 std::vector<Constant*> Indices;
6491 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6492 for (; I != E && isa<Constant>(*I); ++I)
6493 Indices.push_back(cast<Constant>(*I));
6494
6495 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006496 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006497
6498 // Replace all uses of the GEP with the new constexpr...
6499 return ReplaceInstUsesWith(GEP, CE);
6500 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006501 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6502 if (!isa<PointerType>(X->getType())) {
6503 // Not interesting. Source pointer must be a cast from pointer.
6504 } else if (HasZeroPointerIndex) {
6505 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6506 // into : GEP [10 x ubyte]* X, long 0, ...
6507 //
6508 // This occurs when the program declares an array extern like "int X[];"
6509 //
6510 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6511 const PointerType *XTy = cast<PointerType>(X->getType());
6512 if (const ArrayType *XATy =
6513 dyn_cast<ArrayType>(XTy->getElementType()))
6514 if (const ArrayType *CATy =
6515 dyn_cast<ArrayType>(CPTy->getElementType()))
6516 if (CATy->getElementType() == XATy->getElementType()) {
6517 // At this point, we know that the cast source type is a pointer
6518 // to an array of the same type as the destination pointer
6519 // array. Because the array type is never stepped over (there
6520 // is a leading zero) we can fold the cast into this GEP.
6521 GEP.setOperand(0, X);
6522 return &GEP;
6523 }
6524 } else if (GEP.getNumOperands() == 2) {
6525 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006526 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6527 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006528 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6529 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6530 if (isa<ArrayType>(SrcElTy) &&
6531 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6532 TD->getTypeSize(ResElTy)) {
6533 Value *V = InsertNewInstBefore(
6534 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6535 GEP.getOperand(1), GEP.getName()), GEP);
6536 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006537 }
Chris Lattner2a893292005-09-13 18:36:04 +00006538
6539 // Transform things like:
6540 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6541 // (where tmp = 8*tmp2) into:
6542 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6543
6544 if (isa<ArrayType>(SrcElTy) &&
6545 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6546 uint64_t ArrayEltSize =
6547 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6548
6549 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6550 // allow either a mul, shift, or constant here.
6551 Value *NewIdx = 0;
6552 ConstantInt *Scale = 0;
6553 if (ArrayEltSize == 1) {
6554 NewIdx = GEP.getOperand(1);
6555 Scale = ConstantInt::get(NewIdx->getType(), 1);
6556 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006557 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006558 Scale = CI;
6559 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6560 if (Inst->getOpcode() == Instruction::Shl &&
6561 isa<ConstantInt>(Inst->getOperand(1))) {
6562 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6563 if (Inst->getType()->isSigned())
6564 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6565 else
6566 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6567 NewIdx = Inst->getOperand(0);
6568 } else if (Inst->getOpcode() == Instruction::Mul &&
6569 isa<ConstantInt>(Inst->getOperand(1))) {
6570 Scale = cast<ConstantInt>(Inst->getOperand(1));
6571 NewIdx = Inst->getOperand(0);
6572 }
6573 }
6574
6575 // If the index will be to exactly the right offset with the scale taken
6576 // out, perform the transformation.
6577 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6578 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6579 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006580 (int64_t)C->getRawValue() /
6581 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006582 else
6583 Scale = ConstantUInt::get(Scale->getType(),
6584 Scale->getRawValue() / ArrayEltSize);
6585 if (Scale->getRawValue() != 1) {
6586 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6587 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6588 NewIdx = InsertNewInstBefore(Sc, GEP);
6589 }
6590
6591 // Insert the new GEP instruction.
6592 Instruction *Idx =
6593 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6594 NewIdx, GEP.getName());
6595 Idx = InsertNewInstBefore(Idx, GEP);
6596 return new CastInst(Idx, GEP.getType());
6597 }
6598 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006599 }
Chris Lattnerca081252001-12-14 16:52:21 +00006600 }
6601
Chris Lattnerca081252001-12-14 16:52:21 +00006602 return 0;
6603}
6604
Chris Lattner1085bdf2002-11-04 16:18:53 +00006605Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6606 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6607 if (AI.isArrayAllocation()) // Check C != 1
6608 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6609 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006610 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006611
6612 // Create and insert the replacement instruction...
6613 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006614 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006615 else {
6616 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006617 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006618 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006619
6620 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006621
Chris Lattner1085bdf2002-11-04 16:18:53 +00006622 // Scan to the end of the allocation instructions, to skip over a block of
6623 // allocas if possible...
6624 //
6625 BasicBlock::iterator It = New;
6626 while (isa<AllocationInst>(*It)) ++It;
6627
6628 // Now that I is pointing to the first non-allocation-inst in the block,
6629 // insert our getelementptr instruction...
6630 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006631 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6632 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6633 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006634
6635 // Now make everything use the getelementptr instead of the original
6636 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006637 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006638 } else if (isa<UndefValue>(AI.getArraySize())) {
6639 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006640 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006641
6642 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6643 // Note that we only do this for alloca's, because malloc should allocate and
6644 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006645 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006646 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006647 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6648
Chris Lattner1085bdf2002-11-04 16:18:53 +00006649 return 0;
6650}
6651
Chris Lattner8427bff2003-12-07 01:24:23 +00006652Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6653 Value *Op = FI.getOperand(0);
6654
6655 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6656 if (CastInst *CI = dyn_cast<CastInst>(Op))
6657 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6658 FI.setOperand(0, CI->getOperand(0));
6659 return &FI;
6660 }
6661
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006662 // free undef -> unreachable.
6663 if (isa<UndefValue>(Op)) {
6664 // Insert a new store to null because we cannot modify the CFG here.
6665 new StoreInst(ConstantBool::True,
6666 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6667 return EraseInstFromFunction(FI);
6668 }
6669
Chris Lattnerf3a36602004-02-28 04:57:37 +00006670 // If we have 'free null' delete the instruction. This can happen in stl code
6671 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006672 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006673 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006674
Chris Lattner8427bff2003-12-07 01:24:23 +00006675 return 0;
6676}
6677
6678
Chris Lattner72684fe2005-01-31 05:51:45 +00006679/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006680static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6681 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006682 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006683
6684 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006685 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006686 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006687
Chris Lattnerebca4762006-04-02 05:37:12 +00006688 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6689 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006690 // If the source is an array, the code below will not succeed. Check to
6691 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6692 // constants.
6693 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6694 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6695 if (ASrcTy->getNumElements() != 0) {
6696 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6697 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6698 SrcTy = cast<PointerType>(CastOp->getType());
6699 SrcPTy = SrcTy->getElementType();
6700 }
6701
Chris Lattnerebca4762006-04-02 05:37:12 +00006702 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6703 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006704 // Do not allow turning this into a load of an integer, which is then
6705 // casted to a pointer, this pessimizes pointer analysis a lot.
6706 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006707 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006708 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006709
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006710 // Okay, we are casting from one integer or pointer type to another of
6711 // the same size. Instead of casting the pointer before the load, cast
6712 // the result of the loaded value.
6713 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6714 CI->getName(),
6715 LI.isVolatile()),LI);
6716 // Now cast the result of the load.
6717 return new CastInst(NewLoad, LI.getType());
6718 }
Chris Lattner35e24772004-07-13 01:49:43 +00006719 }
6720 }
6721 return 0;
6722}
6723
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006724/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006725/// from this value cannot trap. If it is not obviously safe to load from the
6726/// specified pointer, we do a quick local scan of the basic block containing
6727/// ScanFrom, to determine if the address is already accessed.
6728static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6729 // If it is an alloca or global variable, it is always safe to load from.
6730 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6731
6732 // Otherwise, be a little bit agressive by scanning the local block where we
6733 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006734 // from/to. If so, the previous load or store would have already trapped,
6735 // so there is no harm doing an extra load (also, CSE will later eliminate
6736 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006737 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6738
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006739 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006740 --BBI;
6741
6742 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6743 if (LI->getOperand(0) == V) return true;
6744 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6745 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006746
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006747 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006748 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006749}
6750
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006751Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6752 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006753
Chris Lattnera9d84e32005-05-01 04:24:53 +00006754 // load (cast X) --> cast (load X) iff safe
6755 if (CastInst *CI = dyn_cast<CastInst>(Op))
6756 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6757 return Res;
6758
6759 // None of the following transforms are legal for volatile loads.
6760 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006761
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006762 if (&LI.getParent()->front() != &LI) {
6763 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006764 // If the instruction immediately before this is a store to the same
6765 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006766 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6767 if (SI->getOperand(1) == LI.getOperand(0))
6768 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006769 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6770 if (LIB->getOperand(0) == LI.getOperand(0))
6771 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006772 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006773
6774 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6775 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6776 isa<UndefValue>(GEPI->getOperand(0))) {
6777 // Insert a new store to null instruction before the load to indicate
6778 // that this code is not reachable. We do this instead of inserting
6779 // an unreachable instruction directly because we cannot modify the
6780 // CFG.
6781 new StoreInst(UndefValue::get(LI.getType()),
6782 Constant::getNullValue(Op->getType()), &LI);
6783 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6784 }
6785
Chris Lattner81a7a232004-10-16 18:11:37 +00006786 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006787 // load null/undef -> undef
6788 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006789 // Insert a new store to null instruction before the load to indicate that
6790 // this code is not reachable. We do this instead of inserting an
6791 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006792 new StoreInst(UndefValue::get(LI.getType()),
6793 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006794 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006795 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006796
Chris Lattner81a7a232004-10-16 18:11:37 +00006797 // Instcombine load (constant global) into the value loaded.
6798 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6799 if (GV->isConstant() && !GV->isExternal())
6800 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006801
Chris Lattner81a7a232004-10-16 18:11:37 +00006802 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6803 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6804 if (CE->getOpcode() == Instruction::GetElementPtr) {
6805 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6806 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006807 if (Constant *V =
6808 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006809 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006810 if (CE->getOperand(0)->isNullValue()) {
6811 // Insert a new store to null instruction before the load to indicate
6812 // that this code is not reachable. We do this instead of inserting
6813 // an unreachable instruction directly because we cannot modify the
6814 // CFG.
6815 new StoreInst(UndefValue::get(LI.getType()),
6816 Constant::getNullValue(Op->getType()), &LI);
6817 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6818 }
6819
Chris Lattner81a7a232004-10-16 18:11:37 +00006820 } else if (CE->getOpcode() == Instruction::Cast) {
6821 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6822 return Res;
6823 }
6824 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006825
Chris Lattnera9d84e32005-05-01 04:24:53 +00006826 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006827 // Change select and PHI nodes to select values instead of addresses: this
6828 // helps alias analysis out a lot, allows many others simplifications, and
6829 // exposes redundancy in the code.
6830 //
6831 // Note that we cannot do the transformation unless we know that the
6832 // introduced loads cannot trap! Something like this is valid as long as
6833 // the condition is always false: load (select bool %C, int* null, int* %G),
6834 // but it would not be valid if we transformed it to load from null
6835 // unconditionally.
6836 //
6837 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6838 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006839 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6840 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006841 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006842 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006843 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006844 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006845 return new SelectInst(SI->getCondition(), V1, V2);
6846 }
6847
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006848 // load (select (cond, null, P)) -> load P
6849 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6850 if (C->isNullValue()) {
6851 LI.setOperand(0, SI->getOperand(2));
6852 return &LI;
6853 }
6854
6855 // load (select (cond, P, null)) -> load P
6856 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6857 if (C->isNullValue()) {
6858 LI.setOperand(0, SI->getOperand(1));
6859 return &LI;
6860 }
6861
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006862 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6863 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006864 bool Safe = PN->getParent() == LI.getParent();
6865
6866 // Scan all of the instructions between the PHI and the load to make
6867 // sure there are no instructions that might possibly alter the value
6868 // loaded from the PHI.
6869 if (Safe) {
6870 BasicBlock::iterator I = &LI;
6871 for (--I; !isa<PHINode>(I); --I)
6872 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6873 Safe = false;
6874 break;
6875 }
6876 }
6877
6878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006879 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006880 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006881 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006882
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006883 if (Safe) {
6884 // Create the PHI.
6885 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6886 InsertNewInstBefore(NewPN, *PN);
6887 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6888
6889 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6890 BasicBlock *BB = PN->getIncomingBlock(i);
6891 Value *&TheLoad = LoadMap[BB];
6892 if (TheLoad == 0) {
6893 Value *InVal = PN->getIncomingValue(i);
6894 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6895 InVal->getName()+".val"),
6896 *BB->getTerminator());
6897 }
6898 NewPN->addIncoming(TheLoad, BB);
6899 }
6900 return ReplaceInstUsesWith(LI, NewPN);
6901 }
6902 }
6903 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006904 return 0;
6905}
6906
Chris Lattner72684fe2005-01-31 05:51:45 +00006907/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6908/// when possible.
6909static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6910 User *CI = cast<User>(SI.getOperand(1));
6911 Value *CastOp = CI->getOperand(0);
6912
6913 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6914 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6915 const Type *SrcPTy = SrcTy->getElementType();
6916
6917 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6918 // If the source is an array, the code below will not succeed. Check to
6919 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6920 // constants.
6921 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6922 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6923 if (ASrcTy->getNumElements() != 0) {
6924 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6925 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6926 SrcTy = cast<PointerType>(CastOp->getType());
6927 SrcPTy = SrcTy->getElementType();
6928 }
6929
6930 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006931 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006932 IC.getTargetData().getTypeSize(DestPTy)) {
6933
6934 // Okay, we are casting from one integer or pointer type to another of
6935 // the same size. Instead of casting the pointer before the store, cast
6936 // the value to be stored.
6937 Value *NewCast;
6938 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6939 NewCast = ConstantExpr::getCast(C, SrcPTy);
6940 else
6941 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6942 SrcPTy,
6943 SI.getOperand(0)->getName()+".c"), SI);
6944
6945 return new StoreInst(NewCast, CastOp);
6946 }
6947 }
6948 }
6949 return 0;
6950}
6951
Chris Lattner31f486c2005-01-31 05:36:43 +00006952Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6953 Value *Val = SI.getOperand(0);
6954 Value *Ptr = SI.getOperand(1);
6955
6956 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006957 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006958 ++NumCombined;
6959 return 0;
6960 }
6961
Chris Lattner5997cf92006-02-08 03:25:32 +00006962 // Do really simple DSE, to catch cases where there are several consequtive
6963 // stores to the same location, separated by a few arithmetic operations. This
6964 // situation often occurs with bitfield accesses.
6965 BasicBlock::iterator BBI = &SI;
6966 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6967 --ScanInsts) {
6968 --BBI;
6969
6970 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6971 // Prev store isn't volatile, and stores to the same location?
6972 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6973 ++NumDeadStore;
6974 ++BBI;
6975 EraseInstFromFunction(*PrevSI);
6976 continue;
6977 }
6978 break;
6979 }
6980
Chris Lattnerdab43b22006-05-26 19:19:20 +00006981 // If this is a load, we have to stop. However, if the loaded value is from
6982 // the pointer we're loading and is producing the pointer we're storing,
6983 // then *this* store is dead (X = load P; store X -> P).
6984 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6985 if (LI == Val && LI->getOperand(0) == Ptr) {
6986 EraseInstFromFunction(SI);
6987 ++NumCombined;
6988 return 0;
6989 }
6990 // Otherwise, this is a load from some other location. Stores before it
6991 // may not be dead.
6992 break;
6993 }
6994
Chris Lattner5997cf92006-02-08 03:25:32 +00006995 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00006996 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00006997 break;
6998 }
6999
7000
7001 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007002
7003 // store X, null -> turns into 'unreachable' in SimplifyCFG
7004 if (isa<ConstantPointerNull>(Ptr)) {
7005 if (!isa<UndefValue>(Val)) {
7006 SI.setOperand(0, UndefValue::get(Val->getType()));
7007 if (Instruction *U = dyn_cast<Instruction>(Val))
7008 WorkList.push_back(U); // Dropped a use.
7009 ++NumCombined;
7010 }
7011 return 0; // Do not modify these!
7012 }
7013
7014 // store undef, Ptr -> noop
7015 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007016 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007017 ++NumCombined;
7018 return 0;
7019 }
7020
Chris Lattner72684fe2005-01-31 05:51:45 +00007021 // If the pointer destination is a cast, see if we can fold the cast into the
7022 // source instead.
7023 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7024 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7025 return Res;
7026 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7027 if (CE->getOpcode() == Instruction::Cast)
7028 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7029 return Res;
7030
Chris Lattner219175c2005-09-12 23:23:25 +00007031
7032 // If this store is the last instruction in the basic block, and if the block
7033 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007034 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007035 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7036 if (BI->isUnconditional()) {
7037 // Check to see if the successor block has exactly two incoming edges. If
7038 // so, see if the other predecessor contains a store to the same location.
7039 // if so, insert a PHI node (if needed) and move the stores down.
7040 BasicBlock *Dest = BI->getSuccessor(0);
7041
7042 pred_iterator PI = pred_begin(Dest);
7043 BasicBlock *Other = 0;
7044 if (*PI != BI->getParent())
7045 Other = *PI;
7046 ++PI;
7047 if (PI != pred_end(Dest)) {
7048 if (*PI != BI->getParent())
7049 if (Other)
7050 Other = 0;
7051 else
7052 Other = *PI;
7053 if (++PI != pred_end(Dest))
7054 Other = 0;
7055 }
7056 if (Other) { // If only one other pred...
7057 BBI = Other->getTerminator();
7058 // Make sure this other block ends in an unconditional branch and that
7059 // there is an instruction before the branch.
7060 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7061 BBI != Other->begin()) {
7062 --BBI;
7063 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7064
7065 // If this instruction is a store to the same location.
7066 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7067 // Okay, we know we can perform this transformation. Insert a PHI
7068 // node now if we need it.
7069 Value *MergedVal = OtherStore->getOperand(0);
7070 if (MergedVal != SI.getOperand(0)) {
7071 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7072 PN->reserveOperandSpace(2);
7073 PN->addIncoming(SI.getOperand(0), SI.getParent());
7074 PN->addIncoming(OtherStore->getOperand(0), Other);
7075 MergedVal = InsertNewInstBefore(PN, Dest->front());
7076 }
7077
7078 // Advance to a place where it is safe to insert the new store and
7079 // insert it.
7080 BBI = Dest->begin();
7081 while (isa<PHINode>(BBI)) ++BBI;
7082 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7083 OtherStore->isVolatile()), *BBI);
7084
7085 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007086 EraseInstFromFunction(SI);
7087 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007088 ++NumCombined;
7089 return 0;
7090 }
7091 }
7092 }
7093 }
7094
Chris Lattner31f486c2005-01-31 05:36:43 +00007095 return 0;
7096}
7097
7098
Chris Lattner9eef8a72003-06-04 04:46:00 +00007099Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7100 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007101 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007102 BasicBlock *TrueDest;
7103 BasicBlock *FalseDest;
7104 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7105 !isa<Constant>(X)) {
7106 // Swap Destinations and condition...
7107 BI.setCondition(X);
7108 BI.setSuccessor(0, FalseDest);
7109 BI.setSuccessor(1, TrueDest);
7110 return &BI;
7111 }
7112
7113 // Cannonicalize setne -> seteq
7114 Instruction::BinaryOps Op; Value *Y;
7115 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7116 TrueDest, FalseDest)))
7117 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7118 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7119 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7120 std::string Name = I->getName(); I->setName("");
7121 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7122 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007123 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007124 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007125 BI.setSuccessor(0, FalseDest);
7126 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007127 removeFromWorkList(I);
7128 I->getParent()->getInstList().erase(I);
7129 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007130 return &BI;
7131 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007132
Chris Lattner9eef8a72003-06-04 04:46:00 +00007133 return 0;
7134}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007135
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007136Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7137 Value *Cond = SI.getCondition();
7138 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7139 if (I->getOpcode() == Instruction::Add)
7140 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7141 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7142 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007143 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007144 AddRHS));
7145 SI.setOperand(0, I->getOperand(0));
7146 WorkList.push_back(I);
7147 return &SI;
7148 }
7149 }
7150 return 0;
7151}
7152
Chris Lattner6bc98652006-03-05 00:22:33 +00007153/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7154/// is to leave as a vector operation.
7155static bool CheapToScalarize(Value *V, bool isConstant) {
7156 if (isa<ConstantAggregateZero>(V))
7157 return true;
7158 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7159 if (isConstant) return true;
7160 // If all elts are the same, we can extract.
7161 Constant *Op0 = C->getOperand(0);
7162 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7163 if (C->getOperand(i) != Op0)
7164 return false;
7165 return true;
7166 }
7167 Instruction *I = dyn_cast<Instruction>(V);
7168 if (!I) return false;
7169
7170 // Insert element gets simplified to the inserted element or is deleted if
7171 // this is constant idx extract element and its a constant idx insertelt.
7172 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7173 isa<ConstantInt>(I->getOperand(2)))
7174 return true;
7175 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7176 return true;
7177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7178 if (BO->hasOneUse() &&
7179 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7180 CheapToScalarize(BO->getOperand(1), isConstant)))
7181 return true;
7182
7183 return false;
7184}
7185
Chris Lattner12249be2006-05-25 23:48:38 +00007186/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7187/// elements into values that are larger than the #elts in the input.
7188static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7189 unsigned NElts = SVI->getType()->getNumElements();
7190 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7191 return std::vector<unsigned>(NElts, 0);
7192 if (isa<UndefValue>(SVI->getOperand(2)))
7193 return std::vector<unsigned>(NElts, 2*NElts);
7194
7195 std::vector<unsigned> Result;
7196 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7197 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7198 if (isa<UndefValue>(CP->getOperand(i)))
7199 Result.push_back(NElts*2); // undef -> 8
7200 else
7201 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7202 return Result;
7203}
7204
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007205/// FindScalarElement - Given a vector and an element number, see if the scalar
7206/// value is already around as a register, for example if it were inserted then
7207/// extracted from the vector.
7208static Value *FindScalarElement(Value *V, unsigned EltNo) {
7209 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7210 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007211 unsigned Width = PTy->getNumElements();
7212 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007213 return UndefValue::get(PTy->getElementType());
7214
7215 if (isa<UndefValue>(V))
7216 return UndefValue::get(PTy->getElementType());
7217 else if (isa<ConstantAggregateZero>(V))
7218 return Constant::getNullValue(PTy->getElementType());
7219 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7220 return CP->getOperand(EltNo);
7221 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7222 // If this is an insert to a variable element, we don't know what it is.
7223 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7224 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7225
7226 // If this is an insert to the element we are looking for, return the
7227 // inserted value.
7228 if (EltNo == IIElt) return III->getOperand(1);
7229
7230 // Otherwise, the insertelement doesn't modify the value, recurse on its
7231 // vector input.
7232 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007233 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007234 unsigned InEl = getShuffleMask(SVI)[EltNo];
7235 if (InEl < Width)
7236 return FindScalarElement(SVI->getOperand(0), InEl);
7237 else if (InEl < Width*2)
7238 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7239 else
7240 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007241 }
7242
7243 // Otherwise, we don't know.
7244 return 0;
7245}
7246
Robert Bocchinoa8352962006-01-13 22:48:06 +00007247Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007248
Chris Lattner92346c32006-03-31 18:25:14 +00007249 // If packed val is undef, replace extract with scalar undef.
7250 if (isa<UndefValue>(EI.getOperand(0)))
7251 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7252
7253 // If packed val is constant 0, replace extract with scalar 0.
7254 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7255 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7256
Robert Bocchinoa8352962006-01-13 22:48:06 +00007257 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7258 // If packed val is constant with uniform operands, replace EI
7259 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007260 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007261 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007262 if (C->getOperand(i) != op0) {
7263 op0 = 0;
7264 break;
7265 }
7266 if (op0)
7267 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007268 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007269
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007270 // If extracting a specified index from the vector, see if we can recursively
7271 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007272 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007273 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7274 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007275 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007276
Chris Lattner83f65782006-05-25 22:53:38 +00007277 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007278 if (I->hasOneUse()) {
7279 // Push extractelement into predecessor operation if legal and
7280 // profitable to do so
7281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007282 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7283 if (CheapToScalarize(BO, isConstantElt)) {
7284 ExtractElementInst *newEI0 =
7285 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7286 EI.getName()+".lhs");
7287 ExtractElementInst *newEI1 =
7288 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7289 EI.getName()+".rhs");
7290 InsertNewInstBefore(newEI0, EI);
7291 InsertNewInstBefore(newEI1, EI);
7292 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7293 }
7294 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007295 Value *Ptr = InsertCastBefore(I->getOperand(0),
7296 PointerType::get(EI.getType()), EI);
7297 GetElementPtrInst *GEP =
7298 new GetElementPtrInst(Ptr, EI.getOperand(1),
7299 I->getName() + ".gep");
7300 InsertNewInstBefore(GEP, EI);
7301 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007302 }
7303 }
7304 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7305 // Extracting the inserted element?
7306 if (IE->getOperand(2) == EI.getOperand(1))
7307 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7308 // If the inserted and extracted elements are constants, they must not
7309 // be the same value, extract from the pre-inserted value instead.
7310 if (isa<Constant>(IE->getOperand(2)) &&
7311 isa<Constant>(EI.getOperand(1))) {
7312 AddUsesToWorkList(EI);
7313 EI.setOperand(0, IE->getOperand(0));
7314 return &EI;
7315 }
7316 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7317 // If this is extracting an element from a shufflevector, figure out where
7318 // it came from and extract from the appropriate input element instead.
7319 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007320 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7321 Value *Src;
7322 if (SrcIdx < SVI->getType()->getNumElements())
7323 Src = SVI->getOperand(0);
7324 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7325 SrcIdx -= SVI->getType()->getNumElements();
7326 Src = SVI->getOperand(1);
7327 } else {
7328 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007329 }
Chris Lattner12249be2006-05-25 23:48:38 +00007330 return new ExtractElementInst(Src,
7331 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007332 }
7333 }
Chris Lattner83f65782006-05-25 22:53:38 +00007334 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007335 return 0;
7336}
7337
Chris Lattner90951862006-04-16 00:51:47 +00007338/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7339/// elements from either LHS or RHS, return the shuffle mask and true.
7340/// Otherwise, return false.
7341static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7342 std::vector<Constant*> &Mask) {
7343 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7344 "Invalid CollectSingleShuffleElements");
7345 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7346
7347 if (isa<UndefValue>(V)) {
7348 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7349 return true;
7350 } else if (V == LHS) {
7351 for (unsigned i = 0; i != NumElts; ++i)
7352 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7353 return true;
7354 } else if (V == RHS) {
7355 for (unsigned i = 0; i != NumElts; ++i)
7356 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7357 return true;
7358 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7359 // If this is an insert of an extract from some other vector, include it.
7360 Value *VecOp = IEI->getOperand(0);
7361 Value *ScalarOp = IEI->getOperand(1);
7362 Value *IdxOp = IEI->getOperand(2);
7363
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007364 if (!isa<ConstantInt>(IdxOp))
7365 return false;
7366 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7367
7368 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7369 // Okay, we can handle this if the vector we are insertinting into is
7370 // transitively ok.
7371 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7372 // If so, update the mask to reflect the inserted undef.
7373 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7374 return true;
7375 }
7376 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7377 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007378 EI->getOperand(0)->getType() == V->getType()) {
7379 unsigned ExtractedIdx =
7380 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007381
7382 // This must be extracting from either LHS or RHS.
7383 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7384 // Okay, we can handle this if the vector we are insertinting into is
7385 // transitively ok.
7386 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7387 // If so, update the mask to reflect the inserted value.
7388 if (EI->getOperand(0) == LHS) {
7389 Mask[InsertedIdx & (NumElts-1)] =
7390 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7391 } else {
7392 assert(EI->getOperand(0) == RHS);
7393 Mask[InsertedIdx & (NumElts-1)] =
7394 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7395
7396 }
7397 return true;
7398 }
7399 }
7400 }
7401 }
7402 }
7403 // TODO: Handle shufflevector here!
7404
7405 return false;
7406}
7407
7408/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7409/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7410/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007411static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007412 Value *&RHS) {
7413 assert(isa<PackedType>(V->getType()) &&
7414 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007415 "Invalid shuffle!");
7416 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7417
7418 if (isa<UndefValue>(V)) {
7419 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7420 return V;
7421 } else if (isa<ConstantAggregateZero>(V)) {
7422 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7423 return V;
7424 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7425 // If this is an insert of an extract from some other vector, include it.
7426 Value *VecOp = IEI->getOperand(0);
7427 Value *ScalarOp = IEI->getOperand(1);
7428 Value *IdxOp = IEI->getOperand(2);
7429
7430 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7431 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7432 EI->getOperand(0)->getType() == V->getType()) {
7433 unsigned ExtractedIdx =
7434 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7435 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7436
7437 // Either the extracted from or inserted into vector must be RHSVec,
7438 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007439 if (EI->getOperand(0) == RHS || RHS == 0) {
7440 RHS = EI->getOperand(0);
7441 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007442 Mask[InsertedIdx & (NumElts-1)] =
7443 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7444 return V;
7445 }
7446
Chris Lattner90951862006-04-16 00:51:47 +00007447 if (VecOp == RHS) {
7448 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007449 // Everything but the extracted element is replaced with the RHS.
7450 for (unsigned i = 0; i != NumElts; ++i) {
7451 if (i != InsertedIdx)
7452 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7453 }
7454 return V;
7455 }
Chris Lattner90951862006-04-16 00:51:47 +00007456
7457 // If this insertelement is a chain that comes from exactly these two
7458 // vectors, return the vector and the effective shuffle.
7459 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7460 return EI->getOperand(0);
7461
Chris Lattner39fac442006-04-15 01:39:45 +00007462 }
7463 }
7464 }
Chris Lattner90951862006-04-16 00:51:47 +00007465 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007466
7467 // Otherwise, can't do anything fancy. Return an identity vector.
7468 for (unsigned i = 0; i != NumElts; ++i)
7469 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7470 return V;
7471}
7472
7473Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7474 Value *VecOp = IE.getOperand(0);
7475 Value *ScalarOp = IE.getOperand(1);
7476 Value *IdxOp = IE.getOperand(2);
7477
7478 // If the inserted element was extracted from some other vector, and if the
7479 // indexes are constant, try to turn this into a shufflevector operation.
7480 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7481 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7482 EI->getOperand(0)->getType() == IE.getType()) {
7483 unsigned NumVectorElts = IE.getType()->getNumElements();
7484 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7485 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7486
7487 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7488 return ReplaceInstUsesWith(IE, VecOp);
7489
7490 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7491 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7492
7493 // If we are extracting a value from a vector, then inserting it right
7494 // back into the same place, just use the input vector.
7495 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7496 return ReplaceInstUsesWith(IE, VecOp);
7497
7498 // We could theoretically do this for ANY input. However, doing so could
7499 // turn chains of insertelement instructions into a chain of shufflevector
7500 // instructions, and right now we do not merge shufflevectors. As such,
7501 // only do this in a situation where it is clear that there is benefit.
7502 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7503 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7504 // the values of VecOp, except then one read from EIOp0.
7505 // Build a new shuffle mask.
7506 std::vector<Constant*> Mask;
7507 if (isa<UndefValue>(VecOp))
7508 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7509 else {
7510 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7511 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7512 NumVectorElts));
7513 }
7514 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7515 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7516 ConstantPacked::get(Mask));
7517 }
7518
7519 // If this insertelement isn't used by some other insertelement, turn it
7520 // (and any insertelements it points to), into one big shuffle.
7521 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7522 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007523 Value *RHS = 0;
7524 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7525 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7526 // We now have a shuffle of LHS, RHS, Mask.
7527 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007528 }
7529 }
7530 }
7531
7532 return 0;
7533}
7534
7535
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007536Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7537 Value *LHS = SVI.getOperand(0);
7538 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007539 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007540
7541 bool MadeChange = false;
7542
Chris Lattner12249be2006-05-25 23:48:38 +00007543 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007544 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7545
Chris Lattner39fac442006-04-15 01:39:45 +00007546 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7547 // the undef, change them to undefs.
7548
Chris Lattner12249be2006-05-25 23:48:38 +00007549 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7550 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7551 if (LHS == RHS || isa<UndefValue>(LHS)) {
7552 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007553 // shuffle(undef,undef,mask) -> undef.
7554 return ReplaceInstUsesWith(SVI, LHS);
7555 }
7556
Chris Lattner12249be2006-05-25 23:48:38 +00007557 // Remap any references to RHS to use LHS.
7558 std::vector<Constant*> Elts;
7559 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007560 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007561 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007562 else {
7563 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7564 (Mask[i] < e && isa<UndefValue>(LHS)))
7565 Mask[i] = 2*e; // Turn into undef.
7566 else
7567 Mask[i] &= (e-1); // Force to LHS.
7568 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7569 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007570 }
Chris Lattner12249be2006-05-25 23:48:38 +00007571 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007572 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007573 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007574 LHS = SVI.getOperand(0);
7575 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007576 MadeChange = true;
7577 }
7578
Chris Lattner0e477162006-05-26 00:29:06 +00007579 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007580 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007581
Chris Lattner12249be2006-05-25 23:48:38 +00007582 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7583 if (Mask[i] >= e*2) continue; // Ignore undef values.
7584 // Is this an identity shuffle of the LHS value?
7585 isLHSID &= (Mask[i] == i);
7586
7587 // Is this an identity shuffle of the RHS value?
7588 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007589 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007590
Chris Lattner12249be2006-05-25 23:48:38 +00007591 // Eliminate identity shuffles.
7592 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7593 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007594
Chris Lattner0e477162006-05-26 00:29:06 +00007595 // If the LHS is a shufflevector itself, see if we can combine it with this
7596 // one without producing an unusual shuffle. Here we are really conservative:
7597 // we are absolutely afraid of producing a shuffle mask not in the input
7598 // program, because the code gen may not be smart enough to turn a merged
7599 // shuffle into two specific shuffles: it may produce worse code. As such,
7600 // we only merge two shuffles if the result is one of the two input shuffle
7601 // masks. In this case, merging the shuffles just removes one instruction,
7602 // which we know is safe. This is good for things like turning:
7603 // (splat(splat)) -> splat.
7604 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7605 if (isa<UndefValue>(RHS)) {
7606 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7607
7608 std::vector<unsigned> NewMask;
7609 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7610 if (Mask[i] >= 2*e)
7611 NewMask.push_back(2*e);
7612 else
7613 NewMask.push_back(LHSMask[Mask[i]]);
7614
7615 // If the result mask is equal to the src shuffle or this shuffle mask, do
7616 // the replacement.
7617 if (NewMask == LHSMask || NewMask == Mask) {
7618 std::vector<Constant*> Elts;
7619 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7620 if (NewMask[i] >= e*2) {
7621 Elts.push_back(UndefValue::get(Type::UIntTy));
7622 } else {
7623 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7624 }
7625 }
7626 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7627 LHSSVI->getOperand(1),
7628 ConstantPacked::get(Elts));
7629 }
7630 }
7631 }
7632
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007633 return MadeChange ? &SVI : 0;
7634}
7635
7636
Robert Bocchinoa8352962006-01-13 22:48:06 +00007637
Chris Lattner99f48c62002-09-02 04:59:56 +00007638void InstCombiner::removeFromWorkList(Instruction *I) {
7639 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7640 WorkList.end());
7641}
7642
Chris Lattner39c98bb2004-12-08 23:43:58 +00007643
7644/// TryToSinkInstruction - Try to move the specified instruction from its
7645/// current block into the beginning of DestBlock, which can only happen if it's
7646/// safe to move the instruction past all of the instructions between it and the
7647/// end of its block.
7648static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7649 assert(I->hasOneUse() && "Invariants didn't hold!");
7650
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007651 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7652 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007653
Chris Lattner39c98bb2004-12-08 23:43:58 +00007654 // Do not sink alloca instructions out of the entry block.
7655 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7656 return false;
7657
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007658 // We can only sink load instructions if there is nothing between the load and
7659 // the end of block that could change the value.
7660 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007661 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7662 Scan != E; ++Scan)
7663 if (Scan->mayWriteToMemory())
7664 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007665 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007666
7667 BasicBlock::iterator InsertPos = DestBlock->begin();
7668 while (isa<PHINode>(InsertPos)) ++InsertPos;
7669
Chris Lattner9f269e42005-08-08 19:11:57 +00007670 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007671 ++NumSunkInst;
7672 return true;
7673}
7674
Chris Lattner1443bc52006-05-11 17:11:52 +00007675/// OptimizeConstantExpr - Given a constant expression and target data layout
7676/// information, symbolically evaluation the constant expr to something simpler
7677/// if possible.
7678static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7679 if (!TD) return CE;
7680
7681 Constant *Ptr = CE->getOperand(0);
7682 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7683 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7684 // If this is a constant expr gep that is effectively computing an
7685 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7686 bool isFoldableGEP = true;
7687 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7688 if (!isa<ConstantInt>(CE->getOperand(i)))
7689 isFoldableGEP = false;
7690 if (isFoldableGEP) {
7691 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7692 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7693 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7694 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7695 return ConstantExpr::getCast(C, CE->getType());
7696 }
7697 }
7698
7699 return CE;
7700}
7701
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007702
7703/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7704/// all reachable code to the worklist.
7705///
7706/// This has a couple of tricks to make the code faster and more powerful. In
7707/// particular, we constant fold and DCE instructions as we go, to avoid adding
7708/// them to the worklist (this significantly speeds up instcombine on code where
7709/// many instructions are dead or constant). Additionally, if we find a branch
7710/// whose condition is a known constant, we only visit the reachable successors.
7711///
7712static void AddReachableCodeToWorklist(BasicBlock *BB,
7713 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007714 std::vector<Instruction*> &WorkList,
7715 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007716 // We have now visited this block! If we've already been here, bail out.
7717 if (!Visited.insert(BB).second) return;
7718
7719 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7720 Instruction *Inst = BBI++;
7721
7722 // DCE instruction if trivially dead.
7723 if (isInstructionTriviallyDead(Inst)) {
7724 ++NumDeadInst;
7725 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7726 Inst->eraseFromParent();
7727 continue;
7728 }
7729
7730 // ConstantProp instruction if trivially constant.
7731 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007732 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7733 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007734 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7735 Inst->replaceAllUsesWith(C);
7736 ++NumConstProp;
7737 Inst->eraseFromParent();
7738 continue;
7739 }
7740
7741 WorkList.push_back(Inst);
7742 }
7743
7744 // Recursively visit successors. If this is a branch or switch on a constant,
7745 // only visit the reachable successor.
7746 TerminatorInst *TI = BB->getTerminator();
7747 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7748 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7749 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007750 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7751 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007752 return;
7753 }
7754 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7755 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7756 // See if this is an explicit destination.
7757 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7758 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007759 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007760 return;
7761 }
7762
7763 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00007764 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007765 return;
7766 }
7767 }
7768
7769 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00007770 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007771}
7772
Chris Lattner113f4f42002-06-25 16:13:24 +00007773bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007774 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007775 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007776
Chris Lattner4ed40f72005-07-07 20:40:38 +00007777 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007778 // Do a depth-first traversal of the function, populate the worklist with
7779 // the reachable instructions. Ignore blocks that are not reachable. Keep
7780 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00007781 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00007782 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007783
Chris Lattner4ed40f72005-07-07 20:40:38 +00007784 // Do a quick scan over the function. If we find any blocks that are
7785 // unreachable, remove any instructions inside of them. This prevents
7786 // the instcombine code from having to deal with some bad special cases.
7787 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7788 if (!Visited.count(BB)) {
7789 Instruction *Term = BB->getTerminator();
7790 while (Term != BB->begin()) { // Remove instrs bottom-up
7791 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007792
Chris Lattner4ed40f72005-07-07 20:40:38 +00007793 DEBUG(std::cerr << "IC: DCE: " << *I);
7794 ++NumDeadInst;
7795
7796 if (!I->use_empty())
7797 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7798 I->eraseFromParent();
7799 }
7800 }
7801 }
Chris Lattnerca081252001-12-14 16:52:21 +00007802
7803 while (!WorkList.empty()) {
7804 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7805 WorkList.pop_back();
7806
Chris Lattner1443bc52006-05-11 17:11:52 +00007807 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007808 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007809 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007810 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007811 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007812 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007813
Chris Lattnercd517ff2005-01-28 19:32:01 +00007814 DEBUG(std::cerr << "IC: DCE: " << *I);
7815
7816 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007817 removeFromWorkList(I);
7818 continue;
7819 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007820
Chris Lattner1443bc52006-05-11 17:11:52 +00007821 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00007822 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007823 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7824 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00007825 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7826
Chris Lattner1443bc52006-05-11 17:11:52 +00007827 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00007828 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007829 ReplaceInstUsesWith(*I, C);
7830
Chris Lattner99f48c62002-09-02 04:59:56 +00007831 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007832 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00007833 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007834 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007835 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007836
Chris Lattner39c98bb2004-12-08 23:43:58 +00007837 // See if we can trivially sink this instruction to a successor basic block.
7838 if (I->hasOneUse()) {
7839 BasicBlock *BB = I->getParent();
7840 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7841 if (UserParent != BB) {
7842 bool UserIsSuccessor = false;
7843 // See if the user is one of our successors.
7844 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7845 if (*SI == UserParent) {
7846 UserIsSuccessor = true;
7847 break;
7848 }
7849
7850 // If the user is one of our immediate successors, and if that successor
7851 // only has us as a predecessors (we'd have to split the critical edge
7852 // otherwise), we can keep going.
7853 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7854 next(pred_begin(UserParent)) == pred_end(UserParent))
7855 // Okay, the CFG is simple enough, try to sink this instruction.
7856 Changed |= TryToSinkInstruction(I, UserParent);
7857 }
7858 }
7859
Chris Lattnerca081252001-12-14 16:52:21 +00007860 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007861 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007862 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007863 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007864 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007865 DEBUG(std::cerr << "IC: Old = " << *I
7866 << " New = " << *Result);
7867
Chris Lattner396dbfe2004-06-09 05:08:07 +00007868 // Everything uses the new instruction now.
7869 I->replaceAllUsesWith(Result);
7870
7871 // Push the new instruction and any users onto the worklist.
7872 WorkList.push_back(Result);
7873 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007874
7875 // Move the name to the new instruction first...
7876 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007877 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007878
7879 // Insert the new instruction into the basic block...
7880 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007881 BasicBlock::iterator InsertPos = I;
7882
7883 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7884 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7885 ++InsertPos;
7886
7887 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007888
Chris Lattner63d75af2004-05-01 23:27:23 +00007889 // Make sure that we reprocess all operands now that we reduced their
7890 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007891 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7892 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7893 WorkList.push_back(OpI);
7894
Chris Lattner396dbfe2004-06-09 05:08:07 +00007895 // Instructions can end up on the worklist more than once. Make sure
7896 // we do not process an instruction that has been deleted.
7897 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007898
7899 // Erase the old instruction.
7900 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007901 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007902 DEBUG(std::cerr << "IC: MOD = " << *I);
7903
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007904 // If the instruction was modified, it's possible that it is now dead.
7905 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007906 if (isInstructionTriviallyDead(I)) {
7907 // Make sure we process all operands now that we are reducing their
7908 // use counts.
7909 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7910 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7911 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007912
Chris Lattner63d75af2004-05-01 23:27:23 +00007913 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007914 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007915 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007916 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007917 } else {
7918 WorkList.push_back(Result);
7919 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007920 }
Chris Lattner053c0932002-05-14 15:24:07 +00007921 }
Chris Lattner260ab202002-04-18 17:39:14 +00007922 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007923 }
7924 }
7925
Chris Lattner260ab202002-04-18 17:39:14 +00007926 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007927}
7928
Brian Gaeke38b79e82004-07-27 17:43:21 +00007929FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007930 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007931}
Brian Gaeke960707c2003-11-11 22:41:34 +00007932