blob: e5f2d9294eb442c21385df92281c41afe2217d6c [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
91
Chris Lattner99f48c62002-09-02 04:59:56 +000092 // removeFromWorkList - remove all instances of I from the worklist.
93 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000094 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000095 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000096
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000098 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +000099 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000100 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000101 }
102
Chris Lattner69193f92004-04-05 01:30:19 +0000103 TargetData &getTargetData() const { return *TD; }
104
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // Visitation implementation - Implement instruction combining for different
106 // instruction types. The semantics are as follows:
107 // Return Value:
108 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000109 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000110 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000111 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000112 Instruction *visitAdd(BinaryOperator &I);
113 Instruction *visitSub(BinaryOperator &I);
114 Instruction *visitMul(BinaryOperator &I);
115 Instruction *visitDiv(BinaryOperator &I);
116 Instruction *visitRem(BinaryOperator &I);
117 Instruction *visitAnd(BinaryOperator &I);
118 Instruction *visitOr (BinaryOperator &I);
119 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000120 Instruction *visitSetCondInst(SetCondInst &I);
121 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
122
Chris Lattner0798af32005-01-13 20:14:25 +0000123 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
124 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000125 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000126 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
127 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000129 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
130 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000131 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 Instruction *visitCallInst(CallInst &CI);
133 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000134 Instruction *visitPHINode(PHINode &PN);
135 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000136 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000137 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000138 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000139 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000140 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000141 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000142 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000143 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000144 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000145
146 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000147 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148
Chris Lattner970c33a2003-06-19 17:00:31 +0000149 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000150 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000151 bool transformConstExprCastCall(CallSite CS);
152
Chris Lattner69193f92004-04-05 01:30:19 +0000153 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 // InsertNewInstBefore - insert an instruction New before instruction Old
155 // in the program. Add the new instruction to the worklist.
156 //
Chris Lattner623826c2004-09-28 21:48:02 +0000157 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000158 assert(New && New->getParent() == 0 &&
159 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 BasicBlock *BB = Old.getParent();
161 BB->getInstList().insert(&Old, New); // Insert inst
162 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000163 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000164 }
165
Chris Lattner7e794272004-09-24 15:21:34 +0000166 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
167 /// This also adds the cast to the worklist. Finally, this returns the
168 /// cast.
169 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
170 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000171
Chris Lattnere79d2492006-04-06 19:19:17 +0000172 if (Constant *CV = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CV, Ty);
174
Chris Lattner7e794272004-09-24 15:21:34 +0000175 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
176 WorkList.push_back(C);
177 return C;
178 }
179
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000180 // ReplaceInstUsesWith - This method is to be used when an instruction is
181 // found to be dead, replacable with another preexisting expression. Here
182 // we add all uses of I to the worklist, replace all uses of I with the new
183 // value, then return I, so that the inst combiner will know that I was
184 // modified.
185 //
186 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000187 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000188 if (&I != V) {
189 I.replaceAllUsesWith(V);
190 return &I;
191 } else {
192 // If we are replacing the instruction with itself, this must be in a
193 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000194 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000195 return &I;
196 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000197 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000198
Chris Lattner2590e512006-02-07 06:56:34 +0000199 // UpdateValueUsesWith - This method is to be used when an value is
200 // found to be replacable with another preexisting expression or was
201 // updated. Here we add all uses of I to the worklist, replace all uses of
202 // I with the new value (unless the instruction was just updated), then
203 // return true, so that the inst combiner will know that I was modified.
204 //
205 bool UpdateValueUsesWith(Value *Old, Value *New) {
206 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
207 if (Old != New)
208 Old->replaceAllUsesWith(New);
209 if (Instruction *I = dyn_cast<Instruction>(Old))
210 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000211 if (Instruction *I = dyn_cast<Instruction>(New))
212 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000213 return true;
214 }
215
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 // EraseInstFromFunction - When dealing with an instruction that has side
217 // effects or produces a void value, we can't rely on DCE to delete the
218 // instruction. Instead, visit methods should return the value returned by
219 // this function.
220 Instruction *EraseInstFromFunction(Instruction &I) {
221 assert(I.use_empty() && "Cannot erase instruction that is used!");
222 AddUsesToWorkList(I);
223 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000224 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000225 return 0; // Don't do anything with FI
226 }
227
Chris Lattner3ac7c262003-08-13 20:16:26 +0000228 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000229 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
230 /// InsertBefore instruction. This is specialized a bit to avoid inserting
231 /// casts that are known to not do anything...
232 ///
233 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
234 Instruction *InsertBefore);
235
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000237 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000239
Chris Lattner0157e7f2006-02-11 09:31:47 +0000240 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
241 uint64_t &KnownZero, uint64_t &KnownOne,
242 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000243
244 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
245 // PHI node as operand #0, see if we can fold the instruction into the PHI
246 // (which is only possible if all operands to the PHI are constants).
247 Instruction *FoldOpIntoPhi(Instruction &I);
248
Chris Lattner7515cab2004-11-14 19:13:23 +0000249 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
250 // operator and they all are only used by the PHI, PHI together their
251 // inputs, and do the operation once, to the result of the PHI.
252 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
253
Chris Lattnerba1cb382003-09-19 17:17:26 +0000254 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
255 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000256
257 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
258 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000259 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
260 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000261 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000262 Instruction *MatchBSwap(BinaryOperator &I);
263
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000264 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000265 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000266
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000267 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000268}
269
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000271// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272static unsigned getComplexity(Value *V) {
273 if (isa<Instruction>(V)) {
274 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000275 return 3;
276 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000278 if (isa<Argument>(V)) return 3;
279 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280}
Chris Lattner260ab202002-04-18 17:39:14 +0000281
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282// isOnlyUse - Return true if this instruction will be deleted if we stop using
283// it.
284static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000285 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286}
287
Chris Lattnere79e8542004-02-23 06:38:22 +0000288// getPromotedType - Return the specified type promoted as it would be to pass
289// though a va_arg area...
290static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000291 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000292 case Type::SByteTyID:
293 case Type::ShortTyID: return Type::IntTy;
294 case Type::UByteTyID:
295 case Type::UShortTyID: return Type::UIntTy;
296 case Type::FloatTyID: return Type::DoubleTy;
297 default: return Ty;
298 }
299}
300
Chris Lattner567b81f2005-09-13 00:40:14 +0000301/// isCast - If the specified operand is a CastInst or a constant expr cast,
302/// return the operand value, otherwise return null.
303static Value *isCast(Value *V) {
304 if (CastInst *I = dyn_cast<CastInst>(V))
305 return I->getOperand(0);
306 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
307 if (CE->getOpcode() == Instruction::Cast)
308 return CE->getOperand(0);
309 return 0;
310}
311
Chris Lattner1d441ad2006-05-06 09:00:16 +0000312enum CastType {
313 Noop = 0,
314 Truncate = 1,
315 Signext = 2,
316 Zeroext = 3
317};
318
319/// getCastType - In the future, we will split the cast instruction into these
320/// various types. Until then, we have to do the analysis here.
321static CastType getCastType(const Type *Src, const Type *Dest) {
322 assert(Src->isIntegral() && Dest->isIntegral() &&
323 "Only works on integral types!");
324 unsigned SrcSize = Src->getPrimitiveSizeInBits();
325 unsigned DestSize = Dest->getPrimitiveSizeInBits();
326
327 if (SrcSize == DestSize) return Noop;
328 if (SrcSize > DestSize) return Truncate;
329 if (Src->isSigned()) return Signext;
330 return Zeroext;
331}
332
333
334// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
335// instruction.
336//
337static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
338 const Type *DstTy, TargetData *TD) {
339
340 // It is legal to eliminate the instruction if casting A->B->A if the sizes
341 // are identical and the bits don't get reinterpreted (for example
342 // int->float->int would not be allowed).
343 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
344 return true;
345
346 // If we are casting between pointer and integer types, treat pointers as
347 // integers of the appropriate size for the code below.
348 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
349 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
350 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
351
352 // Allow free casting and conversion of sizes as long as the sign doesn't
353 // change...
354 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
355 CastType FirstCast = getCastType(SrcTy, MidTy);
356 CastType SecondCast = getCastType(MidTy, DstTy);
357
358 // Capture the effect of these two casts. If the result is a legal cast,
359 // the CastType is stored here, otherwise a special code is used.
360 static const unsigned CastResult[] = {
361 // First cast is noop
362 0, 1, 2, 3,
363 // First cast is a truncate
364 1, 1, 4, 4, // trunc->extend is not safe to eliminate
365 // First cast is a sign ext
366 2, 5, 2, 4, // signext->zeroext never ok
367 // First cast is a zero ext
368 3, 5, 3, 3,
369 };
370
371 unsigned Result = CastResult[FirstCast*4+SecondCast];
372 switch (Result) {
373 default: assert(0 && "Illegal table value!");
374 case 0:
375 case 1:
376 case 2:
377 case 3:
378 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
379 // truncates, we could eliminate more casts.
380 return (unsigned)getCastType(SrcTy, DstTy) == Result;
381 case 4:
382 return false; // Not possible to eliminate this here.
383 case 5:
384 // Sign or zero extend followed by truncate is always ok if the result
385 // is a truncate or noop.
386 CastType ResultCast = getCastType(SrcTy, DstTy);
387 if (ResultCast == Noop || ResultCast == Truncate)
388 return true;
389 // Otherwise we are still growing the value, we are only safe if the
390 // result will match the sign/zeroextendness of the result.
391 return ResultCast == FirstCast;
392 }
393 }
394
395 // If this is a cast from 'float -> double -> integer', cast from
396 // 'float -> integer' directly, as the value isn't changed by the
397 // float->double conversion.
398 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
399 DstTy->isIntegral() &&
400 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
401 return true;
402
403 // Packed type conversions don't modify bits.
404 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
405 return true;
406
407 return false;
408}
409
410/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
411/// in any code being generated. It does not require codegen if V is simple
412/// enough or if the cast can be folded into other casts.
413static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
414 if (V->getType() == Ty || isa<Constant>(V)) return false;
415
416 // If this is a noop cast, it isn't real codegen.
417 if (V->getType()->isLosslesslyConvertibleTo(Ty))
418 return false;
419
Chris Lattner99155be2006-05-25 23:24:33 +0000420 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000421 if (const CastInst *CI = dyn_cast<CastInst>(V))
422 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
423 TD))
424 return false;
425 return true;
426}
427
428/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
429/// InsertBefore instruction. This is specialized a bit to avoid inserting
430/// casts that are known to not do anything...
431///
432Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
433 Instruction *InsertBefore) {
434 if (V->getType() == DestTy) return V;
435 if (Constant *C = dyn_cast<Constant>(V))
436 return ConstantExpr::getCast(C, DestTy);
437
438 CastInst *CI = new CastInst(V, DestTy, V->getName());
439 InsertNewInstBefore(CI, *InsertBefore);
440 return CI;
441}
442
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000443// SimplifyCommutative - This performs a few simplifications for commutative
444// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000445//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000446// 1. Order operands such that they are listed from right (least complex) to
447// left (most complex). This puts constants before unary operators before
448// binary operators.
449//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
451// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000453bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 bool Changed = false;
455 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
456 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 if (!I.isAssociative()) return Changed;
459 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000460 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
461 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
462 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000463 Constant *Folded = ConstantExpr::get(I.getOpcode(),
464 cast<Constant>(I.getOperand(1)),
465 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 I.setOperand(0, Op->getOperand(0));
467 I.setOperand(1, Folded);
468 return true;
469 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
470 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
471 isOnlyUse(Op) && isOnlyUse(Op1)) {
472 Constant *C1 = cast<Constant>(Op->getOperand(1));
473 Constant *C2 = cast<Constant>(Op1->getOperand(1));
474
475 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000476 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000477 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
478 Op1->getOperand(0),
479 Op1->getName(), &I);
480 WorkList.push_back(New);
481 I.setOperand(0, New);
482 I.setOperand(1, Folded);
483 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000484 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000485 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000486 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000487}
Chris Lattnerca081252001-12-14 16:52:21 +0000488
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
490// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000491//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000492static inline Value *dyn_castNegVal(Value *V) {
493 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000494 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495
Chris Lattner9ad0d552004-12-14 20:08:06 +0000496 // Constants can be considered to be negated values if they can be folded.
497 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
498 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000499 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000500}
501
Chris Lattnerbb74e222003-03-10 23:06:50 +0000502static inline Value *dyn_castNotVal(Value *V) {
503 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000504 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000505
506 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000507 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000508 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509 return 0;
510}
511
Chris Lattner7fb29e12003-03-11 00:12:48 +0000512// dyn_castFoldableMul - If this value is a multiply that can be folded into
513// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000514// non-constant operand of the multiply, and set CST to point to the multiplier.
515// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000516//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000517static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000518 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000519 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000520 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000522 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000523 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000524 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000525 // The multiplier is really 1 << CST.
526 Constant *One = ConstantInt::get(V->getType(), 1);
527 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
528 return I->getOperand(0);
529 }
530 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000532}
Chris Lattner31ae8632002-08-14 17:51:49 +0000533
Chris Lattner0798af32005-01-13 20:14:25 +0000534/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
535/// expression, return it.
536static User *dyn_castGetElementPtr(Value *V) {
537 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
539 if (CE->getOpcode() == Instruction::GetElementPtr)
540 return cast<User>(V);
541 return false;
542}
543
Chris Lattner623826c2004-09-28 21:48:02 +0000544// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000545static ConstantInt *AddOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getAdd(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000548}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000549static ConstantInt *SubOne(ConstantInt *C) {
550 return cast<ConstantInt>(ConstantExpr::getSub(C,
551 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000552}
553
Chris Lattner0157e7f2006-02-11 09:31:47 +0000554/// GetConstantInType - Return a ConstantInt with the specified type and value.
555///
Chris Lattneree0f2802006-02-12 02:07:56 +0000556static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000557 if (Ty->isUnsigned())
558 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000559 else if (Ty->getTypeID() == Type::BoolTyID)
560 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000561 int64_t SVal = Val;
562 SVal <<= 64-Ty->getPrimitiveSizeInBits();
563 SVal >>= 64-Ty->getPrimitiveSizeInBits();
564 return ConstantSInt::get(Ty, SVal);
565}
566
567
Chris Lattner4534dd592006-02-09 07:38:58 +0000568/// ComputeMaskedBits - Determine which of the bits specified in Mask are
569/// known to be either zero or one and return them in the KnownZero/KnownOne
570/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
571/// processing.
572static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
573 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000574 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
575 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000576 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000577 // optimized based on the contradictory assumption that it is non-zero.
578 // Because instcombine aggressively folds operations with undef args anyway,
579 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000580 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
581 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000582 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000583 KnownZero = ~KnownOne & Mask;
584 return;
585 }
586
587 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000588 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000589 return; // Limit search depth.
590
591 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000592 Instruction *I = dyn_cast<Instruction>(V);
593 if (!I) return;
594
Chris Lattnerfb296922006-05-04 17:33:35 +0000595 Mask &= V->getType()->getIntegralTypeMask();
596
Chris Lattner0157e7f2006-02-11 09:31:47 +0000597 switch (I->getOpcode()) {
598 case Instruction::And:
599 // If either the LHS or the RHS are Zero, the result is zero.
600 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
601 Mask &= ~KnownZero;
602 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
605
606 // Output known-1 bits are only known if set in both the LHS & RHS.
607 KnownOne &= KnownOne2;
608 // Output known-0 are known to be clear if zero in either the LHS | RHS.
609 KnownZero |= KnownZero2;
610 return;
611 case Instruction::Or:
612 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
613 Mask &= ~KnownOne;
614 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
617
618 // Output known-0 bits are only known if clear in both the LHS & RHS.
619 KnownZero &= KnownZero2;
620 // Output known-1 are known to be set if set in either the LHS | RHS.
621 KnownOne |= KnownOne2;
622 return;
623 case Instruction::Xor: {
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
627 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628
629 // Output known-0 bits are known if clear or set in both the LHS & RHS.
630 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
631 // Output known-1 are known to be set if set in only one of the LHS, RHS.
632 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
633 KnownZero = KnownZeroOut;
634 return;
635 }
636 case Instruction::Select:
637 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Only known if known in both the LHS and RHS.
643 KnownOne &= KnownOne2;
644 KnownZero &= KnownZero2;
645 return;
646 case Instruction::Cast: {
647 const Type *SrcTy = I->getOperand(0)->getType();
648 if (!SrcTy->isIntegral()) return;
649
650 // If this is an integer truncate or noop, just look in the input.
651 if (SrcTy->getPrimitiveSizeInBits() >=
652 I->getType()->getPrimitiveSizeInBits()) {
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000654 return;
655 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000656
Chris Lattner0157e7f2006-02-11 09:31:47 +0000657 // Sign or Zero extension. Compute the bits in the result that are not
658 // present in the input.
659 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
660 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000661
Chris Lattner0157e7f2006-02-11 09:31:47 +0000662 // Handle zero extension.
663 if (!SrcTy->isSigned()) {
664 Mask &= SrcTy->getIntegralTypeMask();
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 // The top bits are known to be zero.
668 KnownZero |= NewBits;
669 } else {
670 // Sign extension.
671 Mask &= SrcTy->getIntegralTypeMask();
672 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000674
Chris Lattner0157e7f2006-02-11 09:31:47 +0000675 // If the sign bit of the input is known set or clear, then we know the
676 // top bits of the result.
677 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
678 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000679 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680 KnownOne &= ~NewBits;
681 } else if (KnownOne & InSignBit) { // Input sign bit known set
682 KnownOne |= NewBits;
683 KnownZero &= ~NewBits;
684 } else { // Input sign bit unknown
685 KnownZero &= ~NewBits;
686 KnownOne &= ~NewBits;
687 }
688 }
689 return;
690 }
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
693 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
694 Mask >>= SA->getValue();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 KnownZero <<= SA->getValue();
698 KnownOne <<= SA->getValue();
699 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
700 return;
701 }
702 break;
703 case Instruction::Shr:
704 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
705 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
706 // Compute the new bits that are at the top now.
707 uint64_t HighBits = (1ULL << SA->getValue())-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
709
710 if (I->getType()->isUnsigned()) { // Unsigned shift right.
711 Mask <<= SA->getValue();
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= SA->getValue();
715 KnownOne >>= SA->getValue();
716 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000717 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000718 Mask <<= SA->getValue();
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
720 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
721 KnownZero >>= SA->getValue();
722 KnownOne >>= SA->getValue();
723
724 // Handle the sign bits.
725 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
726 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
727
728 if (KnownZero & SignBit) { // New bits are known zero.
729 KnownZero |= HighBits;
730 } else if (KnownOne & SignBit) { // New bits are known one.
731 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000732 }
733 }
734 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000735 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000736 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000737 }
Chris Lattner92a68652006-02-07 08:05:22 +0000738}
739
740/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
741/// this predicate to simplify operations downstream. Mask is known to be zero
742/// for bits that V cannot have.
743static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000744 uint64_t KnownZero, KnownOne;
745 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000748}
749
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750/// ShrinkDemandedConstant - Check to see if the specified operand of the
751/// specified instruction is a constant integer. If so, check to see if there
752/// are any bits set in the constant that are not demanded. If so, shrink the
753/// constant and return true.
754static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
755 uint64_t Demanded) {
756 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
757 if (!OpC) return false;
758
759 // If there are no bits set that aren't demanded, nothing to do.
760 if ((~Demanded & OpC->getZExtValue()) == 0)
761 return false;
762
763 // This is producing any bits that are not needed, shrink the RHS.
764 uint64_t Val = Demanded & OpC->getZExtValue();
765 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
766 return true;
767}
768
Chris Lattneree0f2802006-02-12 02:07:56 +0000769// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
770// set of known zero and one bits, compute the maximum and minimum values that
771// could have the specified known zero and known one bits, returning them in
772// min/max.
773static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
774 uint64_t KnownZero,
775 uint64_t KnownOne,
776 int64_t &Min, int64_t &Max) {
777 uint64_t TypeBits = Ty->getIntegralTypeMask();
778 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
779
780 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
781
782 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783 // bit if it is unknown.
784 Min = KnownOne;
785 Max = KnownOne|UnknownBits;
786
787 if (SignBit & UnknownBits) { // Sign bit is unknown
788 Min |= SignBit;
789 Max &= ~SignBit;
790 }
791
792 // Sign extend the min/max values.
793 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
794 Min = (Min << ShAmt) >> ShAmt;
795 Max = (Max << ShAmt) >> ShAmt;
796}
797
798// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
799// a set of known zero and one bits, compute the maximum and minimum values that
800// could have the specified known zero and known one bits, returning them in
801// min/max.
802static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
803 uint64_t KnownZero,
804 uint64_t KnownOne,
805 uint64_t &Min,
806 uint64_t &Max) {
807 uint64_t TypeBits = Ty->getIntegralTypeMask();
808 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
809
810 // The minimum value is when the unknown bits are all zeros.
811 Min = KnownOne;
812 // The maximum value is when the unknown bits are all ones.
813 Max = KnownOne|UnknownBits;
814}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000815
816
817/// SimplifyDemandedBits - Look at V. At this point, we know that only the
818/// DemandedMask bits of the result of V are ever used downstream. If we can
819/// use this information to simplify V, do so and return true. Otherwise,
820/// analyze the expression and return a mask of KnownOne and KnownZero bits for
821/// the expression (used to simplify the caller). The KnownZero/One bits may
822/// only be accurate for those bits in the DemandedMask.
823bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
824 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000825 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000826 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne = CI->getZExtValue() & DemandedMask;
829 KnownZero = ~KnownOne & DemandedMask;
830 return false;
831 }
832
833 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000834 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 if (Depth != 0) { // Not at the root.
836 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
837 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000838 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000839 }
Chris Lattner2590e512006-02-07 06:56:34 +0000840 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000841 // just set the DemandedMask to all bits.
842 DemandedMask = V->getType()->getIntegralTypeMask();
843 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000844 if (V != UndefValue::get(V->getType()))
845 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
846 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000847 } else if (Depth == 6) { // Limit search depth.
848 return false;
849 }
850
851 Instruction *I = dyn_cast<Instruction>(V);
852 if (!I) return false; // Only analyze instructions.
853
Chris Lattnerfb296922006-05-04 17:33:35 +0000854 DemandedMask &= V->getType()->getIntegralTypeMask();
855
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000857 switch (I->getOpcode()) {
858 default: break;
859 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000860 // If either the LHS or the RHS are Zero, the result is zero.
861 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
862 KnownZero, KnownOne, Depth+1))
863 return true;
864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
865
866 // If something is known zero on the RHS, the bits aren't demanded on the
867 // LHS.
868 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
869 KnownZero2, KnownOne2, Depth+1))
870 return true;
871 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
872
873 // If all of the demanded bits are known one on one side, return the other.
874 // These bits cannot contribute to the result of the 'and'.
875 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
878 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
882 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
883
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000885 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 return UpdateValueUsesWith(I, I);
887
888 // Output known-1 bits are only known if set in both the LHS & RHS.
889 KnownOne &= KnownOne2;
890 // Output known-0 are known to be clear if zero in either the LHS | RHS.
891 KnownZero |= KnownZero2;
892 break;
893 case Instruction::Or:
894 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895 KnownZero, KnownOne, Depth+1))
896 return true;
897 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
899 KnownZero2, KnownOne2, Depth+1))
900 return true;
901 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000905 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000906 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000907 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000909
910 // If all of the potentially set bits on one side are known to be set on
911 // the other side, just use the 'other' side.
912 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
913 (DemandedMask & (~KnownZero)))
914 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000915 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
916 (DemandedMask & (~KnownZero2)))
917 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918
919 // If the RHS is a constant, see if we can simplify it.
920 if (ShrinkDemandedConstant(I, 1, DemandedMask))
921 return UpdateValueUsesWith(I, I);
922
923 // Output known-0 bits are only known if clear in both the LHS & RHS.
924 KnownZero &= KnownZero2;
925 // Output known-1 are known to be set if set in either the LHS | RHS.
926 KnownOne |= KnownOne2;
927 break;
928 case Instruction::Xor: {
929 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
930 KnownZero, KnownOne, Depth+1))
931 return true;
932 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
934 KnownZero2, KnownOne2, Depth+1))
935 return true;
936 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
937
938 // If all of the demanded bits are known zero on one side, return the other.
939 // These bits cannot contribute to the result of the 'xor'.
940 if ((DemandedMask & KnownZero) == DemandedMask)
941 return UpdateValueUsesWith(I, I->getOperand(0));
942 if ((DemandedMask & KnownZero2) == DemandedMask)
943 return UpdateValueUsesWith(I, I->getOperand(1));
944
945 // Output known-0 bits are known if clear or set in both the LHS & RHS.
946 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
947 // Output known-1 are known to be set if set in only one of the LHS, RHS.
948 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
949
950 // If all of the unknown bits are known to be zero on one side or the other
951 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000952 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000953 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
954 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
955 Instruction *Or =
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
957 I->getName());
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000960 }
961 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000962
Chris Lattner5b2edb12006-02-12 08:02:11 +0000963 // If all of the demanded bits on one side are known, and all of the set
964 // bits on that side are also known to be set on the other side, turn this
965 // into an AND, as we know the bits will be cleared.
966 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
967 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
968 if ((KnownOne & KnownOne2) == KnownOne) {
969 Constant *AndC = GetConstantInType(I->getType(),
970 ~KnownOne & DemandedMask);
971 Instruction *And =
972 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
973 InsertNewInstBefore(And, *I);
974 return UpdateValueUsesWith(I, And);
975 }
976 }
977
Chris Lattner0157e7f2006-02-11 09:31:47 +0000978 // If the RHS is a constant, see if we can simplify it.
979 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
980 if (ShrinkDemandedConstant(I, 1, DemandedMask))
981 return UpdateValueUsesWith(I, I);
982
983 KnownZero = KnownZeroOut;
984 KnownOne = KnownOneOut;
985 break;
986 }
987 case Instruction::Select:
988 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
989 KnownZero, KnownOne, Depth+1))
990 return true;
991 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
992 KnownZero2, KnownOne2, Depth+1))
993 return true;
994 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
995 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
996
997 // If the operands are constants, see if we can simplify them.
998 if (ShrinkDemandedConstant(I, 1, DemandedMask))
999 return UpdateValueUsesWith(I, I);
1000 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1001 return UpdateValueUsesWith(I, I);
1002
1003 // Only known if known in both the LHS and RHS.
1004 KnownOne &= KnownOne2;
1005 KnownZero &= KnownZero2;
1006 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001007 case Instruction::Cast: {
1008 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001009 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001010
Chris Lattner0157e7f2006-02-11 09:31:47 +00001011 // If this is an integer truncate or noop, just look in the input.
1012 if (SrcTy->getPrimitiveSizeInBits() >=
1013 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001014 // Cast to bool is a comparison against 0, which demands all bits. We
1015 // can't propagate anything useful up.
1016 if (I->getType() == Type::BoolTy)
1017 break;
1018
Chris Lattner0157e7f2006-02-11 09:31:47 +00001019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 break;
1024 }
1025
1026 // Sign or Zero extension. Compute the bits in the result that are not
1027 // present in the input.
1028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030
1031 // Handle zero extension.
1032 if (!SrcTy->isSigned()) {
1033 DemandedMask &= SrcTy->getIntegralTypeMask();
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 KnownZero, KnownOne, Depth+1))
1036 return true;
1037 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1038 // The top bits are known to be zero.
1039 KnownZero |= NewBits;
1040 } else {
1041 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001042 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1043 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1044
1045 // If any of the sign extended bits are demanded, we know that the sign
1046 // bit is demanded.
1047 if (NewBits & DemandedMask)
1048 InputDemandedBits |= InSignBit;
1049
1050 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 KnownZero, KnownOne, Depth+1))
1052 return true;
1053 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1054
1055 // If the sign bit of the input is known set or clear, then we know the
1056 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001057
Chris Lattner0157e7f2006-02-11 09:31:47 +00001058 // If the input sign bit is known zero, or if the NewBits are not demanded
1059 // convert this into a zero extension.
1060 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001061 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001062 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001063 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001064 I->getOperand(0)->getName());
1065 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001067 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1068 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001069 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001076 }
Chris Lattner2590e512006-02-07 06:56:34 +00001077 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001078 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001079 }
Chris Lattner2590e512006-02-07 06:56:34 +00001080 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001081 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1082 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1083 KnownZero, KnownOne, Depth+1))
1084 return true;
1085 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1086 KnownZero <<= SA->getValue();
1087 KnownOne <<= SA->getValue();
1088 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1089 }
Chris Lattner2590e512006-02-07 06:56:34 +00001090 break;
1091 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001092 // If this is an arithmetic shift right and only the low-bit is set, we can
1093 // always convert this into a logical shr, even if the shift amount is
1094 // variable. The low bit of the shift cannot be an input sign bit unless
1095 // the shift amount is >= the size of the datatype, which is undefined.
1096 if (DemandedMask == 1 && I->getType()->isSigned()) {
1097 // Convert the input to unsigned.
1098 Instruction *NewVal = new CastInst(I->getOperand(0),
1099 I->getType()->getUnsignedVersion(),
1100 I->getOperand(0)->getName());
1101 InsertNewInstBefore(NewVal, *I);
1102 // Perform the unsigned shift right.
1103 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1104 I->getName());
1105 InsertNewInstBefore(NewVal, *I);
1106 // Then cast that to the destination type.
1107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1108 InsertNewInstBefore(NewVal, *I);
1109 return UpdateValueUsesWith(I, NewVal);
1110 }
1111
Chris Lattner0157e7f2006-02-11 09:31:47 +00001112 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1113 unsigned ShAmt = SA->getValue();
1114
1115 // Compute the new bits that are at the top now.
1116 uint64_t HighBits = (1ULL << ShAmt)-1;
1117 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001118 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001119 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001120 if (SimplifyDemandedBits(I->getOperand(0),
1121 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001122 KnownZero, KnownOne, Depth+1))
1123 return true;
1124 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001125 KnownZero &= TypeMask;
1126 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001127 KnownZero >>= ShAmt;
1128 KnownOne >>= ShAmt;
1129 KnownZero |= HighBits; // high bits known zero.
1130 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001131 if (SimplifyDemandedBits(I->getOperand(0),
1132 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001133 KnownZero, KnownOne, Depth+1))
1134 return true;
1135 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001136 KnownZero &= TypeMask;
1137 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001138 KnownZero >>= SA->getValue();
1139 KnownOne >>= SA->getValue();
1140
1141 // Handle the sign bits.
1142 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1143 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1144
1145 // If the input sign bit is known to be zero, or if none of the top bits
1146 // are demanded, turn this into an unsigned shift right.
1147 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1148 // Convert the input to unsigned.
1149 Instruction *NewVal;
1150 NewVal = new CastInst(I->getOperand(0),
1151 I->getType()->getUnsignedVersion(),
1152 I->getOperand(0)->getName());
1153 InsertNewInstBefore(NewVal, *I);
1154 // Perform the unsigned shift right.
1155 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1156 InsertNewInstBefore(NewVal, *I);
1157 // Then cast that to the destination type.
1158 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1159 InsertNewInstBefore(NewVal, *I);
1160 return UpdateValueUsesWith(I, NewVal);
1161 } else if (KnownOne & SignBit) { // New bits are known one.
1162 KnownOne |= HighBits;
1163 }
Chris Lattner2590e512006-02-07 06:56:34 +00001164 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001165 }
Chris Lattner2590e512006-02-07 06:56:34 +00001166 break;
1167 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001168
1169 // If the client is only demanding bits that we know, return the known
1170 // constant.
1171 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1172 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001173 return false;
1174}
1175
Chris Lattner623826c2004-09-28 21:48:02 +00001176// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1177// true when both operands are equal...
1178//
1179static bool isTrueWhenEqual(Instruction &I) {
1180 return I.getOpcode() == Instruction::SetEQ ||
1181 I.getOpcode() == Instruction::SetGE ||
1182 I.getOpcode() == Instruction::SetLE;
1183}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001184
1185/// AssociativeOpt - Perform an optimization on an associative operator. This
1186/// function is designed to check a chain of associative operators for a
1187/// potential to apply a certain optimization. Since the optimization may be
1188/// applicable if the expression was reassociated, this checks the chain, then
1189/// reassociates the expression as necessary to expose the optimization
1190/// opportunity. This makes use of a special Functor, which must define
1191/// 'shouldApply' and 'apply' methods.
1192///
1193template<typename Functor>
1194Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1195 unsigned Opcode = Root.getOpcode();
1196 Value *LHS = Root.getOperand(0);
1197
1198 // Quick check, see if the immediate LHS matches...
1199 if (F.shouldApply(LHS))
1200 return F.apply(Root);
1201
1202 // Otherwise, if the LHS is not of the same opcode as the root, return.
1203 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001204 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001205 // Should we apply this transform to the RHS?
1206 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1207
1208 // If not to the RHS, check to see if we should apply to the LHS...
1209 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1210 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1211 ShouldApply = true;
1212 }
1213
1214 // If the functor wants to apply the optimization to the RHS of LHSI,
1215 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1216 if (ShouldApply) {
1217 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001218
Chris Lattnerb8b97502003-08-13 19:01:45 +00001219 // Now all of the instructions are in the current basic block, go ahead
1220 // and perform the reassociation.
1221 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1222
1223 // First move the selected RHS to the LHS of the root...
1224 Root.setOperand(0, LHSI->getOperand(1));
1225
1226 // Make what used to be the LHS of the root be the user of the root...
1227 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001228 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001229 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1230 return 0;
1231 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001232 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001233 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001234 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1235 BasicBlock::iterator ARI = &Root; ++ARI;
1236 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1237 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001238
1239 // Now propagate the ExtraOperand down the chain of instructions until we
1240 // get to LHSI.
1241 while (TmpLHSI != LHSI) {
1242 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001243 // Move the instruction to immediately before the chain we are
1244 // constructing to avoid breaking dominance properties.
1245 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1246 BB->getInstList().insert(ARI, NextLHSI);
1247 ARI = NextLHSI;
1248
Chris Lattnerb8b97502003-08-13 19:01:45 +00001249 Value *NextOp = NextLHSI->getOperand(1);
1250 NextLHSI->setOperand(1, ExtraOperand);
1251 TmpLHSI = NextLHSI;
1252 ExtraOperand = NextOp;
1253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001254
Chris Lattnerb8b97502003-08-13 19:01:45 +00001255 // Now that the instructions are reassociated, have the functor perform
1256 // the transformation...
1257 return F.apply(Root);
1258 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001259
Chris Lattnerb8b97502003-08-13 19:01:45 +00001260 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1261 }
1262 return 0;
1263}
1264
1265
1266// AddRHS - Implements: X + X --> X << 1
1267struct AddRHS {
1268 Value *RHS;
1269 AddRHS(Value *rhs) : RHS(rhs) {}
1270 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1271 Instruction *apply(BinaryOperator &Add) const {
1272 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1273 ConstantInt::get(Type::UByteTy, 1));
1274 }
1275};
1276
1277// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1278// iff C1&C2 == 0
1279struct AddMaskingAnd {
1280 Constant *C2;
1281 AddMaskingAnd(Constant *c) : C2(c) {}
1282 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001283 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001284 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001285 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001286 }
1287 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001288 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001289 }
1290};
1291
Chris Lattner86102b82005-01-01 16:22:27 +00001292static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001293 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001294 if (isa<CastInst>(I)) {
1295 if (Constant *SOC = dyn_cast<Constant>(SO))
1296 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001297
Chris Lattner86102b82005-01-01 16:22:27 +00001298 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1299 SO->getName() + ".cast"), I);
1300 }
1301
Chris Lattner183b3362004-04-09 19:05:30 +00001302 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001303 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1304 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001305
Chris Lattner183b3362004-04-09 19:05:30 +00001306 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1307 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001308 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1309 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001310 }
1311
1312 Value *Op0 = SO, *Op1 = ConstOperand;
1313 if (!ConstIsRHS)
1314 std::swap(Op0, Op1);
1315 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1317 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1318 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1319 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001320 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001321 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001322 abort();
1323 }
Chris Lattner86102b82005-01-01 16:22:27 +00001324 return IC->InsertNewInstBefore(New, I);
1325}
1326
1327// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1328// constant as the other operand, try to fold the binary operator into the
1329// select arguments. This also works for Cast instructions, which obviously do
1330// not have a second operand.
1331static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1332 InstCombiner *IC) {
1333 // Don't modify shared select instructions
1334 if (!SI->hasOneUse()) return 0;
1335 Value *TV = SI->getOperand(1);
1336 Value *FV = SI->getOperand(2);
1337
1338 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001339 // Bool selects with constant operands can be folded to logical ops.
1340 if (SI->getType() == Type::BoolTy) return 0;
1341
Chris Lattner86102b82005-01-01 16:22:27 +00001342 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1343 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1344
1345 return new SelectInst(SI->getCondition(), SelectTrueVal,
1346 SelectFalseVal);
1347 }
1348 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001349}
1350
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001351
1352/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1353/// node as operand #0, see if we can fold the instruction into the PHI (which
1354/// is only possible if all operands to the PHI are constants).
1355Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1356 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001357 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001358 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001359
Chris Lattner04689872006-09-09 22:02:56 +00001360 // Check to see if all of the operands of the PHI are constants. If there is
1361 // one non-constant value, remember the BB it is. If there is more than one
1362 // bail out.
1363 BasicBlock *NonConstBB = 0;
1364 for (unsigned i = 0; i != NumPHIValues; ++i)
1365 if (!isa<Constant>(PN->getIncomingValue(i))) {
1366 if (NonConstBB) return 0; // More than one non-const value.
1367 NonConstBB = PN->getIncomingBlock(i);
1368
1369 // If the incoming non-constant value is in I's block, we have an infinite
1370 // loop.
1371 if (NonConstBB == I.getParent())
1372 return 0;
1373 }
1374
1375 // If there is exactly one non-constant value, we can insert a copy of the
1376 // operation in that block. However, if this is a critical edge, we would be
1377 // inserting the computation one some other paths (e.g. inside a loop). Only
1378 // do this if the pred block is unconditionally branching into the phi block.
1379 if (NonConstBB) {
1380 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1381 if (!BI || !BI->isUnconditional()) return 0;
1382 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001383
1384 // Okay, we can do the transformation: create the new PHI node.
1385 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1386 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001387 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001388 InsertNewInstBefore(NewPN, *PN);
1389
1390 // Next, add all of the operands to the PHI.
1391 if (I.getNumOperands() == 2) {
1392 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001393 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001394 Value *InV;
1395 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1396 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1397 } else {
1398 assert(PN->getIncomingBlock(i) == NonConstBB);
1399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1400 InV = BinaryOperator::create(BO->getOpcode(),
1401 PN->getIncomingValue(i), C, "phitmp",
1402 NonConstBB->getTerminator());
1403 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1404 InV = new ShiftInst(SI->getOpcode(),
1405 PN->getIncomingValue(i), C, "phitmp",
1406 NonConstBB->getTerminator());
1407 else
1408 assert(0 && "Unknown binop!");
1409
1410 WorkList.push_back(cast<Instruction>(InV));
1411 }
1412 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001413 }
1414 } else {
1415 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1416 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001417 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001418 Value *InV;
1419 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1420 InV = ConstantExpr::getCast(InC, RetTy);
1421 } else {
1422 assert(PN->getIncomingBlock(i) == NonConstBB);
1423 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1424 NonConstBB->getTerminator());
1425 WorkList.push_back(cast<Instruction>(InV));
1426 }
1427 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001428 }
1429 }
1430 return ReplaceInstUsesWith(I, NewPN);
1431}
1432
Chris Lattner113f4f42002-06-25 16:13:24 +00001433Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001434 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001435 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001436
Chris Lattnercf4a9962004-04-10 22:01:55 +00001437 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001438 // X + undef -> undef
1439 if (isa<UndefValue>(RHS))
1440 return ReplaceInstUsesWith(I, RHS);
1441
Chris Lattnercf4a9962004-04-10 22:01:55 +00001442 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001443 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1444 if (RHSC->isNullValue())
1445 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001446 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1447 if (CFP->isExactlyValue(-0.0))
1448 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001449 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001450
Chris Lattnercf4a9962004-04-10 22:01:55 +00001451 // X + (signbit) --> X ^ signbit
1452 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001453 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001454 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001455 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001456 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001457
1458 if (isa<PHINode>(LHS))
1459 if (Instruction *NV = FoldOpIntoPhi(I))
1460 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001461
Chris Lattner330628a2006-01-06 17:59:59 +00001462 ConstantInt *XorRHS = 0;
1463 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001464 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1465 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1466 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1467 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1468
1469 uint64_t C0080Val = 1ULL << 31;
1470 int64_t CFF80Val = -C0080Val;
1471 unsigned Size = 32;
1472 do {
1473 if (TySizeBits > Size) {
1474 bool Found = false;
1475 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1476 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1477 if (RHSSExt == CFF80Val) {
1478 if (XorRHS->getZExtValue() == C0080Val)
1479 Found = true;
1480 } else if (RHSZExt == C0080Val) {
1481 if (XorRHS->getSExtValue() == CFF80Val)
1482 Found = true;
1483 }
1484 if (Found) {
1485 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001486 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001487 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001488 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001489 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001490 Size = 0; // Not a sign ext, but can't be any others either.
1491 goto FoundSExt;
1492 }
1493 }
1494 Size >>= 1;
1495 C0080Val >>= Size;
1496 CFF80Val >>= Size;
1497 } while (Size >= 8);
1498
1499FoundSExt:
1500 const Type *MiddleType = 0;
1501 switch (Size) {
1502 default: break;
1503 case 32: MiddleType = Type::IntTy; break;
1504 case 16: MiddleType = Type::ShortTy; break;
1505 case 8: MiddleType = Type::SByteTy; break;
1506 }
1507 if (MiddleType) {
1508 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1509 InsertNewInstBefore(NewTrunc, I);
1510 return new CastInst(NewTrunc, I.getType());
1511 }
1512 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001513 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001514
Chris Lattnerb8b97502003-08-13 19:01:45 +00001515 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001516 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001518
1519 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1520 if (RHSI->getOpcode() == Instruction::Sub)
1521 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1522 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1523 }
1524 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1525 if (LHSI->getOpcode() == Instruction::Sub)
1526 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1527 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1528 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001529 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001530
Chris Lattner147e9752002-05-08 22:46:53 +00001531 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001532 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001533 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001534
1535 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001536 if (!isa<Constant>(RHS))
1537 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001538 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001539
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001541 ConstantInt *C2;
1542 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1543 if (X == RHS) // X*C + X --> X * (C+1)
1544 return BinaryOperator::createMul(RHS, AddOne(C2));
1545
1546 // X*C1 + X*C2 --> X * (C1+C2)
1547 ConstantInt *C1;
1548 if (X == dyn_castFoldableMul(RHS, C1))
1549 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001550 }
1551
1552 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001553 if (dyn_castFoldableMul(RHS, C2) == LHS)
1554 return BinaryOperator::createMul(LHS, AddOne(C2));
1555
Chris Lattner57c8d992003-02-18 19:57:07 +00001556
Chris Lattnerb8b97502003-08-13 19:01:45 +00001557 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001559 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001560
Chris Lattnerb9cde762003-10-02 15:11:26 +00001561 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001562 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1564 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1565 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001566 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001567
Chris Lattnerbff91d92004-10-08 05:07:56 +00001568 // (X & FF00) + xx00 -> (X+xx00) & FF00
1569 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1570 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1571 if (Anded == CRHS) {
1572 // See if all bits from the first bit set in the Add RHS up are included
1573 // in the mask. First, get the rightmost bit.
1574 uint64_t AddRHSV = CRHS->getRawValue();
1575
1576 // Form a mask of all bits from the lowest bit added through the top.
1577 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001578 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001579
1580 // See if the and mask includes all of these bits.
1581 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattnerbff91d92004-10-08 05:07:56 +00001583 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1584 // Okay, the xform is safe. Insert the new add pronto.
1585 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1586 LHS->getName()), I);
1587 return BinaryOperator::createAnd(NewAdd, C2);
1588 }
1589 }
1590 }
1591
Chris Lattnerd4252a72004-07-30 07:50:03 +00001592 // Try to fold constant add into select arguments.
1593 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001595 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001596 }
1597
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001598 // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1599 {
1600 CastInst* CI = dyn_cast<CastInst>(LHS);
1601 Value* Other = RHS;
1602 if (!CI) {
1603 CI = dyn_cast<CastInst>(RHS);
1604 Other = LHS;
1605 }
1606 if (CI) {
1607 const Type *UIntPtrTy = TD->getIntPtrType();
1608 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
1609 if((CI->getType() == UIntPtrTy || CI->getType() == SIntPtrTy)
1610 && isa<PointerType>(CI->getOperand(0)->getType())) {
1611 Instruction* I2 = new CastInst(CI->getOperand(0), PointerType::get(Type::SByteTy), "ctg", &I);
1612 WorkList.push_back(I2);
1613 I2 = new GetElementPtrInst(I2, Other, "ctg", &I);
1614 WorkList.push_back(I2);
1615 return new CastInst(I2, CI->getType());
1616 }
1617 }
1618 }
1619
Chris Lattner113f4f42002-06-25 16:13:24 +00001620 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001621}
1622
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001623// isSignBit - Return true if the value represented by the constant only has the
1624// highest order bit set.
1625static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001626 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001627 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001628}
1629
Chris Lattner022167f2004-03-13 00:11:49 +00001630/// RemoveNoopCast - Strip off nonconverting casts from the value.
1631///
1632static Value *RemoveNoopCast(Value *V) {
1633 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1634 const Type *CTy = CI->getType();
1635 const Type *OpTy = CI->getOperand(0)->getType();
1636 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001637 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001638 return RemoveNoopCast(CI->getOperand(0));
1639 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1640 return RemoveNoopCast(CI->getOperand(0));
1641 }
1642 return V;
1643}
1644
Chris Lattner113f4f42002-06-25 16:13:24 +00001645Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001646 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001647
Chris Lattnere6794492002-08-12 21:17:25 +00001648 if (Op0 == Op1) // sub X, X -> 0
1649 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001650
Chris Lattnere6794492002-08-12 21:17:25 +00001651 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001652 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001653 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001654
Chris Lattner81a7a232004-10-16 18:11:37 +00001655 if (isa<UndefValue>(Op0))
1656 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1657 if (isa<UndefValue>(Op1))
1658 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1659
Chris Lattner8f2f5982003-11-05 01:06:05 +00001660 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1661 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001662 if (C->isAllOnesValue())
1663 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001664
Chris Lattner8f2f5982003-11-05 01:06:05 +00001665 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001666 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001667 if (match(Op1, m_Not(m_Value(X))))
1668 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001669 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001670 // -((uint)X >> 31) -> ((int)X >> 31)
1671 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001672 if (C->isNullValue()) {
1673 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1674 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001675 if (SI->getOpcode() == Instruction::Shr)
1676 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1677 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001678 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001679 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001680 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001681 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001682 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001683 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001684 // Ok, the transformation is safe. Insert a cast of the incoming
1685 // value, then the new shift, then the new cast.
1686 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1687 SI->getOperand(0)->getName());
1688 Value *InV = InsertNewInstBefore(FirstCast, I);
1689 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1690 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001691 if (NewShift->getType() == I.getType())
1692 return NewShift;
1693 else {
1694 InV = InsertNewInstBefore(NewShift, I);
1695 return new CastInst(NewShift, I.getType());
1696 }
Chris Lattner92295c52004-03-12 23:53:13 +00001697 }
1698 }
Chris Lattner022167f2004-03-13 00:11:49 +00001699 }
Chris Lattner183b3362004-04-09 19:05:30 +00001700
1701 // Try to fold constant sub into select arguments.
1702 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001703 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001704 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001705
1706 if (isa<PHINode>(Op0))
1707 if (Instruction *NV = FoldOpIntoPhi(I))
1708 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001709 }
1710
Chris Lattnera9be4492005-04-07 16:15:25 +00001711 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1712 if (Op1I->getOpcode() == Instruction::Add &&
1713 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001714 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001715 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001716 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001717 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001718 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1719 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1720 // C1-(X+C2) --> (C1-C2)-X
1721 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1722 Op1I->getOperand(0));
1723 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001724 }
1725
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001726 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001727 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1728 // is not used by anyone else...
1729 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001730 if (Op1I->getOpcode() == Instruction::Sub &&
1731 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001732 // Swap the two operands of the subexpr...
1733 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1734 Op1I->setOperand(0, IIOp1);
1735 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001736
Chris Lattner3082c5a2003-02-18 19:28:33 +00001737 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001738 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001739 }
1740
1741 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1742 //
1743 if (Op1I->getOpcode() == Instruction::And &&
1744 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1745 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1746
Chris Lattner396dbfe2004-06-09 05:08:07 +00001747 Value *NewNot =
1748 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001749 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001750 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001751
Chris Lattner0aee4b72004-10-06 15:08:25 +00001752 // -(X sdiv C) -> (X sdiv -C)
1753 if (Op1I->getOpcode() == Instruction::Div)
1754 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001755 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001756 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001757 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001758 ConstantExpr::getNeg(DivRHS));
1759
Chris Lattner57c8d992003-02-18 19:57:07 +00001760 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001761 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001762 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001763 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001764 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001765 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001766 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001767 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001768 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001769
Chris Lattner47060462005-04-07 17:14:51 +00001770 if (!Op0->getType()->isFloatingPoint())
1771 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1772 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001773 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1774 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1775 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1776 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001777 } else if (Op0I->getOpcode() == Instruction::Sub) {
1778 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1779 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001780 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001781
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001782 ConstantInt *C1;
1783 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1784 if (X == Op1) { // X*C - X --> X * (C-1)
1785 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1786 return BinaryOperator::createMul(Op1, CP1);
1787 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001788
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001789 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1790 if (X == dyn_castFoldableMul(Op1, C2))
1791 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1792 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001793 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001794}
1795
Chris Lattnere79e8542004-02-23 06:38:22 +00001796/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1797/// really just returns true if the most significant (sign) bit is set.
1798static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1799 if (RHS->getType()->isSigned()) {
1800 // True if source is LHS < 0 or LHS <= -1
1801 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1802 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1803 } else {
1804 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1805 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1806 // the size of the integer type.
1807 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001808 return RHSC->getValue() ==
1809 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001810 if (Opcode == Instruction::SetGT)
1811 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001812 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001813 }
1814 return false;
1815}
1816
Chris Lattner113f4f42002-06-25 16:13:24 +00001817Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001818 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001819 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001820
Chris Lattner81a7a232004-10-16 18:11:37 +00001821 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1822 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1823
Chris Lattnere6794492002-08-12 21:17:25 +00001824 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001825 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1826 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001827
1828 // ((X << C1)*C2) == (X * (C2 << C1))
1829 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1830 if (SI->getOpcode() == Instruction::Shl)
1831 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001832 return BinaryOperator::createMul(SI->getOperand(0),
1833 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001834
Chris Lattnercce81be2003-09-11 22:24:54 +00001835 if (CI->isNullValue())
1836 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1837 if (CI->equalsInt(1)) // X * 1 == X
1838 return ReplaceInstUsesWith(I, Op0);
1839 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001840 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001841
Chris Lattnercce81be2003-09-11 22:24:54 +00001842 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001843 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1844 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001845 return new ShiftInst(Instruction::Shl, Op0,
1846 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001847 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001848 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001849 if (Op1F->isNullValue())
1850 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001851
Chris Lattner3082c5a2003-02-18 19:28:33 +00001852 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1853 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1854 if (Op1F->getValue() == 1.0)
1855 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1856 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001857
1858 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1859 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1860 isa<ConstantInt>(Op0I->getOperand(1))) {
1861 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1862 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1863 Op1, "tmp");
1864 InsertNewInstBefore(Add, I);
1865 Value *C1C2 = ConstantExpr::getMul(Op1,
1866 cast<Constant>(Op0I->getOperand(1)));
1867 return BinaryOperator::createAdd(Add, C1C2);
1868
1869 }
Chris Lattner183b3362004-04-09 19:05:30 +00001870
1871 // Try to fold constant mul into select arguments.
1872 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001873 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001874 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001875
1876 if (isa<PHINode>(Op0))
1877 if (Instruction *NV = FoldOpIntoPhi(I))
1878 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001879 }
1880
Chris Lattner934a64cf2003-03-10 23:23:04 +00001881 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1882 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001883 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001884
Chris Lattner2635b522004-02-23 05:39:21 +00001885 // If one of the operands of the multiply is a cast from a boolean value, then
1886 // we know the bool is either zero or one, so this is a 'masking' multiply.
1887 // See if we can simplify things based on how the boolean was originally
1888 // formed.
1889 CastInst *BoolCast = 0;
1890 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1891 if (CI->getOperand(0)->getType() == Type::BoolTy)
1892 BoolCast = CI;
1893 if (!BoolCast)
1894 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1895 if (CI->getOperand(0)->getType() == Type::BoolTy)
1896 BoolCast = CI;
1897 if (BoolCast) {
1898 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1899 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1900 const Type *SCOpTy = SCIOp0->getType();
1901
Chris Lattnere79e8542004-02-23 06:38:22 +00001902 // If the setcc is true iff the sign bit of X is set, then convert this
1903 // multiply into a shift/and combination.
1904 if (isa<ConstantInt>(SCIOp1) &&
1905 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001906 // Shift the X value right to turn it into "all signbits".
1907 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001908 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001909 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001910 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001911 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1912 SCIOp0->getName()), I);
1913 }
1914
1915 Value *V =
1916 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1917 BoolCast->getOperand(0)->getName()+
1918 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001919
1920 // If the multiply type is not the same as the source type, sign extend
1921 // or truncate to the multiply type.
1922 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001923 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001924
Chris Lattner2635b522004-02-23 05:39:21 +00001925 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001926 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001927 }
1928 }
1929 }
1930
Chris Lattner113f4f42002-06-25 16:13:24 +00001931 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001932}
1933
Chris Lattner113f4f42002-06-25 16:13:24 +00001934Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001936
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001937 if (isa<UndefValue>(Op0)) // undef / X -> 0
1938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1939 if (isa<UndefValue>(Op1))
1940 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1941
1942 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001943 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001944 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001945 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001946
Chris Lattnere20c3342004-04-26 14:01:59 +00001947 // div X, -1 == -X
1948 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001949 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001950
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001951 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001952 if (LHS->getOpcode() == Instruction::Div)
1953 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001954 // (X / C1) / C2 -> X / (C1*C2)
1955 return BinaryOperator::createDiv(LHS->getOperand(0),
1956 ConstantExpr::getMul(RHS, LHSRHS));
1957 }
1958
Chris Lattner3082c5a2003-02-18 19:28:33 +00001959 // Check to see if this is an unsigned division with an exact power of 2,
1960 // if so, convert to a right shift.
1961 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1962 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001963 if (isPowerOf2_64(Val)) {
1964 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001965 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001966 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001967 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001968
Chris Lattner4ad08352004-10-09 02:50:40 +00001969 // -X/C -> X/-C
1970 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001971 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001972 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1973
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001974 if (!RHS->isNullValue()) {
1975 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001976 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001977 return R;
1978 if (isa<PHINode>(Op0))
1979 if (Instruction *NV = FoldOpIntoPhi(I))
1980 return NV;
1981 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001982 }
1983
Chris Lattnerd79dc792006-09-09 20:26:32 +00001984 // Handle div X, Cond?Y:Z
1985 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1986 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1987 // same basic block, then we replace the select with Y, and the condition of
1988 // the select with false (if the cond value is in the same BB). If the
1989 // select has uses other than the div, this allows them to be simplified
1990 // also.
1991 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1992 if (ST->isNullValue()) {
1993 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1994 if (CondI && CondI->getParent() == I.getParent())
1995 UpdateValueUsesWith(CondI, ConstantBool::False);
1996 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1997 I.setOperand(1, SI->getOperand(2));
1998 else
1999 UpdateValueUsesWith(SI, SI->getOperand(2));
2000 return &I;
2001 }
2002 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2003 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2004 if (ST->isNullValue()) {
2005 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2006 if (CondI && CondI->getParent() == I.getParent())
2007 UpdateValueUsesWith(CondI, ConstantBool::True);
2008 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2009 I.setOperand(1, SI->getOperand(1));
2010 else
2011 UpdateValueUsesWith(SI, SI->getOperand(1));
2012 return &I;
2013 }
2014
2015 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2016 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002017 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2018 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002019 // STO == 0 and SFO == 0 handled above.
Chris Lattner42362612005-04-08 04:03:26 +00002020 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002021 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2022 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00002023 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
2024 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2025 TC, SI->getName()+".t");
2026 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002027
Chris Lattner42362612005-04-08 04:03:26 +00002028 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
2029 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2030 FC, SI->getName()+".f");
2031 FSI = InsertNewInstBefore(FSI, I);
2032 return new SelectInst(SI->getOperand(0), TSI, FSI);
2033 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002034 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002035 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002036
Chris Lattner3082c5a2003-02-18 19:28:33 +00002037 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002038 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002039 if (LHS->equalsInt(0))
2040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2041
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002042 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002043 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002044 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002045 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2046 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002047 const Type *NTy = Op0->getType()->getUnsignedVersion();
2048 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2049 InsertNewInstBefore(LHS, I);
2050 Value *RHS;
2051 if (Constant *R = dyn_cast<Constant>(Op1))
2052 RHS = ConstantExpr::getCast(R, NTy);
2053 else
2054 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2055 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2056 InsertNewInstBefore(Div, I);
2057 return new CastInst(Div, I.getType());
2058 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002059 } else {
2060 // Known to be an unsigned division.
2061 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2062 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2063 if (RHSI->getOpcode() == Instruction::Shl &&
2064 isa<ConstantUInt>(RHSI->getOperand(0))) {
2065 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2066 if (isPowerOf2_64(C1)) {
2067 unsigned C2 = Log2_64(C1);
2068 Value *Add = RHSI->getOperand(1);
2069 if (C2) {
2070 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2071 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2072 "tmp"), I);
2073 }
2074 return new ShiftInst(Instruction::Shr, Op0, Add);
2075 }
2076 }
2077 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002078 }
2079
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002080 return 0;
2081}
2082
2083
Chris Lattner85dda9a2006-03-02 06:50:58 +00002084/// GetFactor - If we can prove that the specified value is at least a multiple
2085/// of some factor, return that factor.
2086static Constant *GetFactor(Value *V) {
2087 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2088 return CI;
2089
2090 // Unless we can be tricky, we know this is a multiple of 1.
2091 Constant *Result = ConstantInt::get(V->getType(), 1);
2092
2093 Instruction *I = dyn_cast<Instruction>(V);
2094 if (!I) return Result;
2095
2096 if (I->getOpcode() == Instruction::Mul) {
2097 // Handle multiplies by a constant, etc.
2098 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2099 GetFactor(I->getOperand(1)));
2100 } else if (I->getOpcode() == Instruction::Shl) {
2101 // (X<<C) -> X * (1 << C)
2102 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2103 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2104 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2105 }
2106 } else if (I->getOpcode() == Instruction::And) {
2107 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2108 // X & 0xFFF0 is known to be a multiple of 16.
2109 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2110 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2111 return ConstantExpr::getShl(Result,
2112 ConstantUInt::get(Type::UByteTy, Zeros));
2113 }
2114 } else if (I->getOpcode() == Instruction::Cast) {
2115 Value *Op = I->getOperand(0);
2116 // Only handle int->int casts.
2117 if (!Op->getType()->isInteger()) return Result;
2118 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2119 }
2120 return Result;
2121}
2122
Chris Lattner113f4f42002-06-25 16:13:24 +00002123Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002125
2126 // 0 % X == 0, we don't need to preserve faults!
2127 if (Constant *LHS = dyn_cast<Constant>(Op0))
2128 if (LHS->isNullValue())
2129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2130
2131 if (isa<UndefValue>(Op0)) // undef % X -> 0
2132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2133 if (isa<UndefValue>(Op1))
2134 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2135
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002136 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002137 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002138 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002139 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002140 // X % -Y -> X % Y
2141 AddUsesToWorkList(I);
2142 I.setOperand(1, RHSNeg);
2143 return &I;
2144 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002145
2146 // If the top bits of both operands are zero (i.e. we can prove they are
2147 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002148 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2149 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002150 const Type *NTy = Op0->getType()->getUnsignedVersion();
2151 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2152 InsertNewInstBefore(LHS, I);
2153 Value *RHS;
2154 if (Constant *R = dyn_cast<Constant>(Op1))
2155 RHS = ConstantExpr::getCast(R, NTy);
2156 else
2157 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2158 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2159 InsertNewInstBefore(Rem, I);
2160 return new CastInst(Rem, I.getType());
2161 }
2162 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002163
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002164 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002165 // X % 0 == undef, we don't need to preserve faults!
2166 if (RHS->equalsInt(0))
2167 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2168
Chris Lattner3082c5a2003-02-18 19:28:33 +00002169 if (RHS->equalsInt(1)) // X % 1 == 0
2170 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2171
2172 // Check to see if this is an unsigned remainder with an exact power of 2,
2173 // if so, convert to a bitwise and.
2174 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002175 if (isPowerOf2_64(C->getValue()))
2176 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002177
Chris Lattnerb70f1412006-02-28 05:49:21 +00002178 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2179 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2180 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2181 return R;
2182 } else if (isa<PHINode>(Op0I)) {
2183 if (Instruction *NV = FoldOpIntoPhi(I))
2184 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002185 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002186
2187 // X*C1%C2 --> 0 iff C1%C2 == 0
2188 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2189 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002190 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002191 }
2192
Chris Lattner2e90b732006-02-05 07:54:04 +00002193 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2194 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2195 if (I.getType()->isUnsigned() &&
2196 RHSI->getOpcode() == Instruction::Shl &&
2197 isa<ConstantUInt>(RHSI->getOperand(0))) {
2198 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2199 if (isPowerOf2_64(C1)) {
2200 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2201 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2202 "tmp"), I);
2203 return BinaryOperator::createAnd(Op0, Add);
2204 }
2205 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002206
2207 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2208 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002209 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2210 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2211 // the same basic block, then we replace the select with Y, and the
2212 // condition of the select with false (if the cond value is in the same
2213 // BB). If the select has uses other than the div, this allows them to be
2214 // simplified also.
2215 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2216 if (ST->isNullValue()) {
2217 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2218 if (CondI && CondI->getParent() == I.getParent())
2219 UpdateValueUsesWith(CondI, ConstantBool::False);
2220 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2221 I.setOperand(1, SI->getOperand(2));
2222 else
2223 UpdateValueUsesWith(SI, SI->getOperand(2));
2224 return &I;
2225 }
2226 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2227 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2228 if (ST->isNullValue()) {
2229 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2230 if (CondI && CondI->getParent() == I.getParent())
2231 UpdateValueUsesWith(CondI, ConstantBool::True);
2232 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2233 I.setOperand(1, SI->getOperand(1));
2234 else
2235 UpdateValueUsesWith(SI, SI->getOperand(1));
2236 return &I;
2237 }
2238
2239
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002240 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2241 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002242 // STO == 0 and SFO == 0 handled above.
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002243
2244 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2245 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2246 SubOne(STO), SI->getName()+".t"), I);
2247 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2248 SubOne(SFO), SI->getName()+".f"), I);
2249 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2250 }
2251 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002252 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002253 }
2254
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002255 return 0;
2256}
2257
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002258// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002259static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002260 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2261 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002262
2263 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002264
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002265 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002266 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002267 int64_t Val = INT64_MAX; // All ones
2268 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2269 return CS->getValue() == Val-1;
2270}
2271
2272// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002273static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002274 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2275 return CU->getValue() == 1;
2276
2277 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002278
2279 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002280 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002281 int64_t Val = -1; // All ones
2282 Val <<= TypeBits-1; // Shift over to the right spot
2283 return CS->getValue() == Val+1;
2284}
2285
Chris Lattner35167c32004-06-09 07:59:58 +00002286// isOneBitSet - Return true if there is exactly one bit set in the specified
2287// constant.
2288static bool isOneBitSet(const ConstantInt *CI) {
2289 uint64_t V = CI->getRawValue();
2290 return V && (V & (V-1)) == 0;
2291}
2292
Chris Lattner8fc5af42004-09-23 21:46:38 +00002293#if 0 // Currently unused
2294// isLowOnes - Return true if the constant is of the form 0+1+.
2295static bool isLowOnes(const ConstantInt *CI) {
2296 uint64_t V = CI->getRawValue();
2297
2298 // There won't be bits set in parts that the type doesn't contain.
2299 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2300
2301 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2302 return U && V && (U & V) == 0;
2303}
2304#endif
2305
2306// isHighOnes - Return true if the constant is of the form 1+0+.
2307// This is the same as lowones(~X).
2308static bool isHighOnes(const ConstantInt *CI) {
2309 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002310 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002311
2312 // There won't be bits set in parts that the type doesn't contain.
2313 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2314
2315 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2316 return U && V && (U & V) == 0;
2317}
2318
2319
Chris Lattner3ac7c262003-08-13 20:16:26 +00002320/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2321/// are carefully arranged to allow folding of expressions such as:
2322///
2323/// (A < B) | (A > B) --> (A != B)
2324///
2325/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2326/// represents that the comparison is true if A == B, and bit value '1' is true
2327/// if A < B.
2328///
2329static unsigned getSetCondCode(const SetCondInst *SCI) {
2330 switch (SCI->getOpcode()) {
2331 // False -> 0
2332 case Instruction::SetGT: return 1;
2333 case Instruction::SetEQ: return 2;
2334 case Instruction::SetGE: return 3;
2335 case Instruction::SetLT: return 4;
2336 case Instruction::SetNE: return 5;
2337 case Instruction::SetLE: return 6;
2338 // True -> 7
2339 default:
2340 assert(0 && "Invalid SetCC opcode!");
2341 return 0;
2342 }
2343}
2344
2345/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2346/// opcode and two operands into either a constant true or false, or a brand new
2347/// SetCC instruction.
2348static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2349 switch (Opcode) {
2350 case 0: return ConstantBool::False;
2351 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2352 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2353 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2354 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2355 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2356 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2357 case 7: return ConstantBool::True;
2358 default: assert(0 && "Illegal SetCCCode!"); return 0;
2359 }
2360}
2361
2362// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2363struct FoldSetCCLogical {
2364 InstCombiner &IC;
2365 Value *LHS, *RHS;
2366 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2367 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2368 bool shouldApply(Value *V) const {
2369 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2370 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2371 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2372 return false;
2373 }
2374 Instruction *apply(BinaryOperator &Log) const {
2375 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2376 if (SCI->getOperand(0) != LHS) {
2377 assert(SCI->getOperand(1) == LHS);
2378 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2379 }
2380
2381 unsigned LHSCode = getSetCondCode(SCI);
2382 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2383 unsigned Code;
2384 switch (Log.getOpcode()) {
2385 case Instruction::And: Code = LHSCode & RHSCode; break;
2386 case Instruction::Or: Code = LHSCode | RHSCode; break;
2387 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002388 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002389 }
2390
2391 Value *RV = getSetCCValue(Code, LHS, RHS);
2392 if (Instruction *I = dyn_cast<Instruction>(RV))
2393 return I;
2394 // Otherwise, it's a constant boolean value...
2395 return IC.ReplaceInstUsesWith(Log, RV);
2396 }
2397};
2398
Chris Lattnerba1cb382003-09-19 17:17:26 +00002399// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2400// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2401// guaranteed to be either a shift instruction or a binary operator.
2402Instruction *InstCombiner::OptAndOp(Instruction *Op,
2403 ConstantIntegral *OpRHS,
2404 ConstantIntegral *AndRHS,
2405 BinaryOperator &TheAnd) {
2406 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002407 Constant *Together = 0;
2408 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002409 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002410
Chris Lattnerba1cb382003-09-19 17:17:26 +00002411 switch (Op->getOpcode()) {
2412 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002413 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002414 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2415 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002416 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002417 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002418 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002419 }
2420 break;
2421 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002422 if (Together == AndRHS) // (X | C) & C --> C
2423 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002424
Chris Lattner86102b82005-01-01 16:22:27 +00002425 if (Op->hasOneUse() && Together != OpRHS) {
2426 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2427 std::string Op0Name = Op->getName(); Op->setName("");
2428 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2429 InsertNewInstBefore(Or, TheAnd);
2430 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002431 }
2432 break;
2433 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002434 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002435 // Adding a one to a single bit bit-field should be turned into an XOR
2436 // of the bit. First thing to check is to see if this AND is with a
2437 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002438 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002439
2440 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002441 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002442
2443 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002444 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002445 // Ok, at this point, we know that we are masking the result of the
2446 // ADD down to exactly one bit. If the constant we are adding has
2447 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002448 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002449
Chris Lattnerba1cb382003-09-19 17:17:26 +00002450 // Check to see if any bits below the one bit set in AndRHSV are set.
2451 if ((AddRHS & (AndRHSV-1)) == 0) {
2452 // If not, the only thing that can effect the output of the AND is
2453 // the bit specified by AndRHSV. If that bit is set, the effect of
2454 // the XOR is to toggle the bit. If it is clear, then the ADD has
2455 // no effect.
2456 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2457 TheAnd.setOperand(0, X);
2458 return &TheAnd;
2459 } else {
2460 std::string Name = Op->getName(); Op->setName("");
2461 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002462 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002463 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002464 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002465 }
2466 }
2467 }
2468 }
2469 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002470
2471 case Instruction::Shl: {
2472 // We know that the AND will not produce any of the bits shifted in, so if
2473 // the anded constant includes them, clear them now!
2474 //
2475 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002476 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2477 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002478
Chris Lattner7e794272004-09-24 15:21:34 +00002479 if (CI == ShlMask) { // Masking out bits that the shift already masks
2480 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2481 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002482 TheAnd.setOperand(1, CI);
2483 return &TheAnd;
2484 }
2485 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002486 }
Chris Lattner2da29172003-09-19 19:05:02 +00002487 case Instruction::Shr:
2488 // We know that the AND will not produce any of the bits shifted in, so if
2489 // the anded constant includes them, clear them now! This only applies to
2490 // unsigned shifts, because a signed shr may bring in set bits!
2491 //
2492 if (AndRHS->getType()->isUnsigned()) {
2493 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002494 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2495 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2496
2497 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2498 return ReplaceInstUsesWith(TheAnd, Op);
2499 } else if (CI != AndRHS) {
2500 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002501 return &TheAnd;
2502 }
Chris Lattner7e794272004-09-24 15:21:34 +00002503 } else { // Signed shr.
2504 // See if this is shifting in some sign extension, then masking it out
2505 // with an and.
2506 if (Op->hasOneUse()) {
2507 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2508 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2509 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002510 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002511 // Make the argument unsigned.
2512 Value *ShVal = Op->getOperand(0);
2513 ShVal = InsertCastBefore(ShVal,
2514 ShVal->getType()->getUnsignedVersion(),
2515 TheAnd);
2516 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2517 OpRHS, Op->getName()),
2518 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002519 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2520 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2521 TheAnd.getName()),
2522 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002523 return new CastInst(ShVal, Op->getType());
2524 }
2525 }
Chris Lattner2da29172003-09-19 19:05:02 +00002526 }
2527 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002528 }
2529 return 0;
2530}
2531
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002532
Chris Lattner6862fbd2004-09-29 17:40:11 +00002533/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2534/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2535/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2536/// insert new instructions.
2537Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2538 bool Inside, Instruction &IB) {
2539 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2540 "Lo is not <= Hi in range emission code!");
2541 if (Inside) {
2542 if (Lo == Hi) // Trivially false.
2543 return new SetCondInst(Instruction::SetNE, V, V);
2544 if (cast<ConstantIntegral>(Lo)->isMinValue())
2545 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002546
Chris Lattner6862fbd2004-09-29 17:40:11 +00002547 Constant *AddCST = ConstantExpr::getNeg(Lo);
2548 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2549 InsertNewInstBefore(Add, IB);
2550 // Convert to unsigned for the comparison.
2551 const Type *UnsType = Add->getType()->getUnsignedVersion();
2552 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2553 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2554 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2555 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2556 }
2557
2558 if (Lo == Hi) // Trivially true.
2559 return new SetCondInst(Instruction::SetEQ, V, V);
2560
2561 Hi = SubOne(cast<ConstantInt>(Hi));
2562 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2563 return new SetCondInst(Instruction::SetGT, V, Hi);
2564
2565 // Emit X-Lo > Hi-Lo-1
2566 Constant *AddCST = ConstantExpr::getNeg(Lo);
2567 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2568 InsertNewInstBefore(Add, IB);
2569 // Convert to unsigned for the comparison.
2570 const Type *UnsType = Add->getType()->getUnsignedVersion();
2571 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2572 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2573 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2574 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2575}
2576
Chris Lattnerb4b25302005-09-18 07:22:02 +00002577// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2578// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2579// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2580// not, since all 1s are not contiguous.
2581static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2582 uint64_t V = Val->getRawValue();
2583 if (!isShiftedMask_64(V)) return false;
2584
2585 // look for the first zero bit after the run of ones
2586 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2587 // look for the first non-zero bit
2588 ME = 64-CountLeadingZeros_64(V);
2589 return true;
2590}
2591
2592
2593
2594/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2595/// where isSub determines whether the operator is a sub. If we can fold one of
2596/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002597///
2598/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2599/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2600/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2601///
2602/// return (A +/- B).
2603///
2604Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2605 ConstantIntegral *Mask, bool isSub,
2606 Instruction &I) {
2607 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2608 if (!LHSI || LHSI->getNumOperands() != 2 ||
2609 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2610
2611 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2612
2613 switch (LHSI->getOpcode()) {
2614 default: return 0;
2615 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002616 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2617 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2618 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2619 break;
2620
2621 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2622 // part, we don't need any explicit masks to take them out of A. If that
2623 // is all N is, ignore it.
2624 unsigned MB, ME;
2625 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002626 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2627 Mask >>= 64-MB+1;
2628 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002629 break;
2630 }
2631 }
Chris Lattneraf517572005-09-18 04:24:45 +00002632 return 0;
2633 case Instruction::Or:
2634 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002635 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2636 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2637 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002638 break;
2639 return 0;
2640 }
2641
2642 Instruction *New;
2643 if (isSub)
2644 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2645 else
2646 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2647 return InsertNewInstBefore(New, I);
2648}
2649
Chris Lattner113f4f42002-06-25 16:13:24 +00002650Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002651 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002653
Chris Lattner81a7a232004-10-16 18:11:37 +00002654 if (isa<UndefValue>(Op1)) // X & undef -> 0
2655 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2656
Chris Lattner86102b82005-01-01 16:22:27 +00002657 // and X, X = X
2658 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002659 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002660
Chris Lattner5b2edb12006-02-12 08:02:11 +00002661 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002662 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002663 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002664 if (!isa<PackedType>(I.getType()) &&
2665 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002666 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002667 return &I;
2668
Chris Lattner86102b82005-01-01 16:22:27 +00002669 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002670 uint64_t AndRHSMask = AndRHS->getZExtValue();
2671 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002672 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002673
Chris Lattnerba1cb382003-09-19 17:17:26 +00002674 // Optimize a variety of ((val OP C1) & C2) combinations...
2675 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2676 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002677 Value *Op0LHS = Op0I->getOperand(0);
2678 Value *Op0RHS = Op0I->getOperand(1);
2679 switch (Op0I->getOpcode()) {
2680 case Instruction::Xor:
2681 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002682 // If the mask is only needed on one incoming arm, push it up.
2683 if (Op0I->hasOneUse()) {
2684 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2685 // Not masking anything out for the LHS, move to RHS.
2686 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2687 Op0RHS->getName()+".masked");
2688 InsertNewInstBefore(NewRHS, I);
2689 return BinaryOperator::create(
2690 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002691 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002692 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002693 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2694 // Not masking anything out for the RHS, move to LHS.
2695 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2696 Op0LHS->getName()+".masked");
2697 InsertNewInstBefore(NewLHS, I);
2698 return BinaryOperator::create(
2699 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2700 }
2701 }
2702
Chris Lattner86102b82005-01-01 16:22:27 +00002703 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002704 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002705 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2706 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2707 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2708 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2709 return BinaryOperator::createAnd(V, AndRHS);
2710 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2711 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002712 break;
2713
2714 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002715 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2716 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2717 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2718 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2719 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002720 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002721 }
2722
Chris Lattner16464b32003-07-23 19:25:52 +00002723 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002724 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002725 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002726 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2727 const Type *SrcTy = CI->getOperand(0)->getType();
2728
Chris Lattner2c14cf72005-08-07 07:03:10 +00002729 // If this is an integer truncation or change from signed-to-unsigned, and
2730 // if the source is an and/or with immediate, transform it. This
2731 // frequently occurs for bitfield accesses.
2732 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2733 if (SrcTy->getPrimitiveSizeInBits() >=
2734 I.getType()->getPrimitiveSizeInBits() &&
2735 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002736 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002737 if (CastOp->getOpcode() == Instruction::And) {
2738 // Change: and (cast (and X, C1) to T), C2
2739 // into : and (cast X to T), trunc(C1)&C2
2740 // This will folds the two ands together, which may allow other
2741 // simplifications.
2742 Instruction *NewCast =
2743 new CastInst(CastOp->getOperand(0), I.getType(),
2744 CastOp->getName()+".shrunk");
2745 NewCast = InsertNewInstBefore(NewCast, I);
2746
2747 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2748 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2749 return BinaryOperator::createAnd(NewCast, C3);
2750 } else if (CastOp->getOpcode() == Instruction::Or) {
2751 // Change: and (cast (or X, C1) to T), C2
2752 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2753 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2754 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2755 return ReplaceInstUsesWith(I, AndRHS);
2756 }
2757 }
Chris Lattner33217db2003-07-23 19:36:21 +00002758 }
Chris Lattner183b3362004-04-09 19:05:30 +00002759
2760 // Try to fold constant and into select arguments.
2761 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002762 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002763 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002764 if (isa<PHINode>(Op0))
2765 if (Instruction *NV = FoldOpIntoPhi(I))
2766 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002767 }
2768
Chris Lattnerbb74e222003-03-10 23:06:50 +00002769 Value *Op0NotVal = dyn_castNotVal(Op0);
2770 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002771
Chris Lattner023a4832004-06-18 06:07:51 +00002772 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2773 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2774
Misha Brukman9c003d82004-07-30 12:50:08 +00002775 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002776 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002777 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2778 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002779 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002780 return BinaryOperator::createNot(Or);
2781 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002782
2783 {
2784 Value *A = 0, *B = 0;
2785 ConstantInt *C1 = 0, *C2 = 0;
2786 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2787 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2788 return ReplaceInstUsesWith(I, Op1);
2789 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2790 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2791 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002792
2793 if (Op0->hasOneUse() &&
2794 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2795 if (A == Op1) { // (A^B)&A -> A&(A^B)
2796 I.swapOperands(); // Simplify below
2797 std::swap(Op0, Op1);
2798 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2799 cast<BinaryOperator>(Op0)->swapOperands();
2800 I.swapOperands(); // Simplify below
2801 std::swap(Op0, Op1);
2802 }
2803 }
2804 if (Op1->hasOneUse() &&
2805 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2806 if (B == Op0) { // B&(A^B) -> B&(B^A)
2807 cast<BinaryOperator>(Op1)->swapOperands();
2808 std::swap(A, B);
2809 }
2810 if (A == Op0) { // A&(A^B) -> A & ~B
2811 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2812 InsertNewInstBefore(NotB, I);
2813 return BinaryOperator::createAnd(A, NotB);
2814 }
2815 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002816 }
2817
Chris Lattner3082c5a2003-02-18 19:28:33 +00002818
Chris Lattner623826c2004-09-28 21:48:02 +00002819 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2820 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002821 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2822 return R;
2823
Chris Lattner623826c2004-09-28 21:48:02 +00002824 Value *LHSVal, *RHSVal;
2825 ConstantInt *LHSCst, *RHSCst;
2826 Instruction::BinaryOps LHSCC, RHSCC;
2827 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2828 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2829 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2830 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002831 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002832 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2833 // Ensure that the larger constant is on the RHS.
2834 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2835 SetCondInst *LHS = cast<SetCondInst>(Op0);
2836 if (cast<ConstantBool>(Cmp)->getValue()) {
2837 std::swap(LHS, RHS);
2838 std::swap(LHSCst, RHSCst);
2839 std::swap(LHSCC, RHSCC);
2840 }
2841
2842 // At this point, we know we have have two setcc instructions
2843 // comparing a value against two constants and and'ing the result
2844 // together. Because of the above check, we know that we only have
2845 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2846 // FoldSetCCLogical check above), that the two constants are not
2847 // equal.
2848 assert(LHSCst != RHSCst && "Compares not folded above?");
2849
2850 switch (LHSCC) {
2851 default: assert(0 && "Unknown integer condition code!");
2852 case Instruction::SetEQ:
2853 switch (RHSCC) {
2854 default: assert(0 && "Unknown integer condition code!");
2855 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2856 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2857 return ReplaceInstUsesWith(I, ConstantBool::False);
2858 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2859 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2860 return ReplaceInstUsesWith(I, LHS);
2861 }
2862 case Instruction::SetNE:
2863 switch (RHSCC) {
2864 default: assert(0 && "Unknown integer condition code!");
2865 case Instruction::SetLT:
2866 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2867 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2868 break; // (X != 13 & X < 15) -> no change
2869 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2870 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2871 return ReplaceInstUsesWith(I, RHS);
2872 case Instruction::SetNE:
2873 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2874 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2875 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2876 LHSVal->getName()+".off");
2877 InsertNewInstBefore(Add, I);
2878 const Type *UnsType = Add->getType()->getUnsignedVersion();
2879 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2880 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2881 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2882 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2883 }
2884 break; // (X != 13 & X != 15) -> no change
2885 }
2886 break;
2887 case Instruction::SetLT:
2888 switch (RHSCC) {
2889 default: assert(0 && "Unknown integer condition code!");
2890 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2891 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2892 return ReplaceInstUsesWith(I, ConstantBool::False);
2893 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2894 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2895 return ReplaceInstUsesWith(I, LHS);
2896 }
2897 case Instruction::SetGT:
2898 switch (RHSCC) {
2899 default: assert(0 && "Unknown integer condition code!");
2900 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2901 return ReplaceInstUsesWith(I, LHS);
2902 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2903 return ReplaceInstUsesWith(I, RHS);
2904 case Instruction::SetNE:
2905 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2906 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2907 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002908 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2909 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002910 }
2911 }
2912 }
2913 }
2914
Chris Lattner3af10532006-05-05 06:39:07 +00002915 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2916 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002917 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002918 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002919 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002920 // Only do this if the casts both really cause code to be generated.
2921 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2922 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002923 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2924 Op1C->getOperand(0),
2925 I.getName());
2926 InsertNewInstBefore(NewOp, I);
2927 return new CastInst(NewOp, I.getType());
2928 }
2929 }
2930
Chris Lattner113f4f42002-06-25 16:13:24 +00002931 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002932}
2933
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002934/// CollectBSwapParts - Look to see if the specified value defines a single byte
2935/// in the result. If it does, and if the specified byte hasn't been filled in
2936/// yet, fill it in and return false.
2937static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2938 Instruction *I = dyn_cast<Instruction>(V);
2939 if (I == 0) return true;
2940
2941 // If this is an or instruction, it is an inner node of the bswap.
2942 if (I->getOpcode() == Instruction::Or)
2943 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2944 CollectBSwapParts(I->getOperand(1), ByteValues);
2945
2946 // If this is a shift by a constant int, and it is "24", then its operand
2947 // defines a byte. We only handle unsigned types here.
2948 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2949 // Not shifting the entire input by N-1 bytes?
2950 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2951 8*(ByteValues.size()-1))
2952 return true;
2953
2954 unsigned DestNo;
2955 if (I->getOpcode() == Instruction::Shl) {
2956 // X << 24 defines the top byte with the lowest of the input bytes.
2957 DestNo = ByteValues.size()-1;
2958 } else {
2959 // X >>u 24 defines the low byte with the highest of the input bytes.
2960 DestNo = 0;
2961 }
2962
2963 // If the destination byte value is already defined, the values are or'd
2964 // together, which isn't a bswap (unless it's an or of the same bits).
2965 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2966 return true;
2967 ByteValues[DestNo] = I->getOperand(0);
2968 return false;
2969 }
2970
2971 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2972 // don't have this.
2973 Value *Shift = 0, *ShiftLHS = 0;
2974 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2975 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2976 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2977 return true;
2978 Instruction *SI = cast<Instruction>(Shift);
2979
2980 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2981 if (ShiftAmt->getRawValue() & 7 ||
2982 ShiftAmt->getRawValue() > 8*ByteValues.size())
2983 return true;
2984
2985 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2986 unsigned DestByte;
2987 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2988 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2989 break;
2990 // Unknown mask for bswap.
2991 if (DestByte == ByteValues.size()) return true;
2992
2993 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2994 unsigned SrcByte;
2995 if (SI->getOpcode() == Instruction::Shl)
2996 SrcByte = DestByte - ShiftBytes;
2997 else
2998 SrcByte = DestByte + ShiftBytes;
2999
3000 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3001 if (SrcByte != ByteValues.size()-DestByte-1)
3002 return true;
3003
3004 // If the destination byte value is already defined, the values are or'd
3005 // together, which isn't a bswap (unless it's an or of the same bits).
3006 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3007 return true;
3008 ByteValues[DestByte] = SI->getOperand(0);
3009 return false;
3010}
3011
3012/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3013/// If so, insert the new bswap intrinsic and return it.
3014Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3015 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3016 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3017 return 0;
3018
3019 /// ByteValues - For each byte of the result, we keep track of which value
3020 /// defines each byte.
3021 std::vector<Value*> ByteValues;
3022 ByteValues.resize(I.getType()->getPrimitiveSize());
3023
3024 // Try to find all the pieces corresponding to the bswap.
3025 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3026 CollectBSwapParts(I.getOperand(1), ByteValues))
3027 return 0;
3028
3029 // Check to see if all of the bytes come from the same value.
3030 Value *V = ByteValues[0];
3031 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3032
3033 // Check to make sure that all of the bytes come from the same value.
3034 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3035 if (ByteValues[i] != V)
3036 return 0;
3037
3038 // If they do then *success* we can turn this into a bswap. Figure out what
3039 // bswap to make it into.
3040 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003041 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003042 if (I.getType() == Type::UShortTy)
3043 FnName = "llvm.bswap.i16";
3044 else if (I.getType() == Type::UIntTy)
3045 FnName = "llvm.bswap.i32";
3046 else if (I.getType() == Type::ULongTy)
3047 FnName = "llvm.bswap.i64";
3048 else
3049 assert(0 && "Unknown integer type!");
3050 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3051
3052 return new CallInst(F, V);
3053}
3054
3055
Chris Lattner113f4f42002-06-25 16:13:24 +00003056Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003057 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003059
Chris Lattner81a7a232004-10-16 18:11:37 +00003060 if (isa<UndefValue>(Op1))
3061 return ReplaceInstUsesWith(I, // X | undef -> -1
3062 ConstantIntegral::getAllOnesValue(I.getType()));
3063
Chris Lattner5b2edb12006-02-12 08:02:11 +00003064 // or X, X = X
3065 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003066 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003067
Chris Lattner5b2edb12006-02-12 08:02:11 +00003068 // See if we can simplify any instructions used by the instruction whose sole
3069 // purpose is to compute bits we don't care about.
3070 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003071 if (!isa<PackedType>(I.getType()) &&
3072 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003073 KnownZero, KnownOne))
3074 return &I;
3075
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003076 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003077 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003078 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003079 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3080 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003081 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3082 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003083 InsertNewInstBefore(Or, I);
3084 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3085 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003086
Chris Lattnerd4252a72004-07-30 07:50:03 +00003087 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3088 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3089 std::string Op0Name = Op0->getName(); Op0->setName("");
3090 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3091 InsertNewInstBefore(Or, I);
3092 return BinaryOperator::createXor(Or,
3093 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003094 }
Chris Lattner183b3362004-04-09 19:05:30 +00003095
3096 // Try to fold constant and into select arguments.
3097 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003098 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003099 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003100 if (isa<PHINode>(Op0))
3101 if (Instruction *NV = FoldOpIntoPhi(I))
3102 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003103 }
3104
Chris Lattner330628a2006-01-06 17:59:59 +00003105 Value *A = 0, *B = 0;
3106 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003107
3108 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3109 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3110 return ReplaceInstUsesWith(I, Op1);
3111 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3112 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3113 return ReplaceInstUsesWith(I, Op0);
3114
Chris Lattnerb7845d62006-07-10 20:25:24 +00003115 // (A | B) | C and A | (B | C) -> bswap if possible.
3116 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003117 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003118 match(Op1, m_Or(m_Value(), m_Value())) ||
3119 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3120 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003121 if (Instruction *BSwap = MatchBSwap(I))
3122 return BSwap;
3123 }
3124
Chris Lattnerb62f5082005-05-09 04:58:36 +00003125 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3126 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003127 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003128 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3129 Op0->setName("");
3130 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3131 }
3132
3133 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3134 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003135 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003136 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3137 Op0->setName("");
3138 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3139 }
3140
Chris Lattner15212982005-09-18 03:42:07 +00003141 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003142 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003143 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3144
3145 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3146 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3147
3148
Chris Lattner01f56c62005-09-18 06:02:59 +00003149 // If we have: ((V + N) & C1) | (V & C2)
3150 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3151 // replace with V+N.
3152 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003153 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003154 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3155 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3156 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003157 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003158 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003159 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003160 return ReplaceInstUsesWith(I, A);
3161 }
3162 // Or commutes, try both ways.
3163 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3164 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3165 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003166 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003167 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003168 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003169 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003170 }
3171 }
3172 }
Chris Lattner812aab72003-08-12 19:11:07 +00003173
Chris Lattnerd4252a72004-07-30 07:50:03 +00003174 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3175 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003176 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003177 ConstantIntegral::getAllOnesValue(I.getType()));
3178 } else {
3179 A = 0;
3180 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003181 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003182 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3183 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003184 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003185 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003186
Misha Brukman9c003d82004-07-30 12:50:08 +00003187 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003188 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3189 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3190 I.getName()+".demorgan"), I);
3191 return BinaryOperator::createNot(And);
3192 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003193 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003194
Chris Lattner3ac7c262003-08-13 20:16:26 +00003195 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003196 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003197 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3198 return R;
3199
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003200 Value *LHSVal, *RHSVal;
3201 ConstantInt *LHSCst, *RHSCst;
3202 Instruction::BinaryOps LHSCC, RHSCC;
3203 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3204 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3205 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3206 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003207 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003208 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3209 // Ensure that the larger constant is on the RHS.
3210 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3211 SetCondInst *LHS = cast<SetCondInst>(Op0);
3212 if (cast<ConstantBool>(Cmp)->getValue()) {
3213 std::swap(LHS, RHS);
3214 std::swap(LHSCst, RHSCst);
3215 std::swap(LHSCC, RHSCC);
3216 }
3217
3218 // At this point, we know we have have two setcc instructions
3219 // comparing a value against two constants and or'ing the result
3220 // together. Because of the above check, we know that we only have
3221 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3222 // FoldSetCCLogical check above), that the two constants are not
3223 // equal.
3224 assert(LHSCst != RHSCst && "Compares not folded above?");
3225
3226 switch (LHSCC) {
3227 default: assert(0 && "Unknown integer condition code!");
3228 case Instruction::SetEQ:
3229 switch (RHSCC) {
3230 default: assert(0 && "Unknown integer condition code!");
3231 case Instruction::SetEQ:
3232 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3233 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3234 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3235 LHSVal->getName()+".off");
3236 InsertNewInstBefore(Add, I);
3237 const Type *UnsType = Add->getType()->getUnsignedVersion();
3238 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3239 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3240 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3241 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3242 }
3243 break; // (X == 13 | X == 15) -> no change
3244
Chris Lattner5c219462005-04-19 06:04:18 +00003245 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3246 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003247 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3248 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3249 return ReplaceInstUsesWith(I, RHS);
3250 }
3251 break;
3252 case Instruction::SetNE:
3253 switch (RHSCC) {
3254 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003255 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3256 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3257 return ReplaceInstUsesWith(I, LHS);
3258 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003259 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003260 return ReplaceInstUsesWith(I, ConstantBool::True);
3261 }
3262 break;
3263 case Instruction::SetLT:
3264 switch (RHSCC) {
3265 default: assert(0 && "Unknown integer condition code!");
3266 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3267 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003268 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3269 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003270 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3271 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3272 return ReplaceInstUsesWith(I, RHS);
3273 }
3274 break;
3275 case Instruction::SetGT:
3276 switch (RHSCC) {
3277 default: assert(0 && "Unknown integer condition code!");
3278 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3279 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3280 return ReplaceInstUsesWith(I, LHS);
3281 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3282 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3283 return ReplaceInstUsesWith(I, ConstantBool::True);
3284 }
3285 }
3286 }
3287 }
Chris Lattner3af10532006-05-05 06:39:07 +00003288
3289 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3290 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003291 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003292 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003293 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003294 // Only do this if the casts both really cause code to be generated.
3295 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3296 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003297 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3298 Op1C->getOperand(0),
3299 I.getName());
3300 InsertNewInstBefore(NewOp, I);
3301 return new CastInst(NewOp, I.getType());
3302 }
3303 }
3304
Chris Lattner15212982005-09-18 03:42:07 +00003305
Chris Lattner113f4f42002-06-25 16:13:24 +00003306 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003307}
3308
Chris Lattnerc2076352004-02-16 01:20:27 +00003309// XorSelf - Implements: X ^ X --> 0
3310struct XorSelf {
3311 Value *RHS;
3312 XorSelf(Value *rhs) : RHS(rhs) {}
3313 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3314 Instruction *apply(BinaryOperator &Xor) const {
3315 return &Xor;
3316 }
3317};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003318
3319
Chris Lattner113f4f42002-06-25 16:13:24 +00003320Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003321 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003323
Chris Lattner81a7a232004-10-16 18:11:37 +00003324 if (isa<UndefValue>(Op1))
3325 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3326
Chris Lattnerc2076352004-02-16 01:20:27 +00003327 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3328 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3329 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003330 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003331 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003332
3333 // See if we can simplify any instructions used by the instruction whose sole
3334 // purpose is to compute bits we don't care about.
3335 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003336 if (!isa<PackedType>(I.getType()) &&
3337 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003338 KnownZero, KnownOne))
3339 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003340
Chris Lattner97638592003-07-23 21:37:07 +00003341 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003342 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003343 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003344 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003345 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003346 return new SetCondInst(SCI->getInverseCondition(),
3347 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003348
Chris Lattner8f2f5982003-11-05 01:06:05 +00003349 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003350 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3351 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003352 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3353 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003354 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003355 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003356 }
Chris Lattner023a4832004-06-18 06:07:51 +00003357
3358 // ~(~X & Y) --> (X | ~Y)
3359 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3360 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3361 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3362 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003363 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003364 Op0I->getOperand(1)->getName()+".not");
3365 InsertNewInstBefore(NotY, I);
3366 return BinaryOperator::createOr(Op0NotVal, NotY);
3367 }
3368 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003369
Chris Lattner97638592003-07-23 21:37:07 +00003370 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003371 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003372 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003373 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003374 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3375 return BinaryOperator::createSub(
3376 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003377 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003378 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003379 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003380 } else if (Op0I->getOpcode() == Instruction::Or) {
3381 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3382 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3383 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3384 // Anything in both C1 and C2 is known to be zero, remove it from
3385 // NewRHS.
3386 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3387 NewRHS = ConstantExpr::getAnd(NewRHS,
3388 ConstantExpr::getNot(CommonBits));
3389 WorkList.push_back(Op0I);
3390 I.setOperand(0, Op0I->getOperand(0));
3391 I.setOperand(1, NewRHS);
3392 return &I;
3393 }
Chris Lattner97638592003-07-23 21:37:07 +00003394 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003395 }
Chris Lattner183b3362004-04-09 19:05:30 +00003396
3397 // Try to fold constant and into select arguments.
3398 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003399 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003400 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003401 if (isa<PHINode>(Op0))
3402 if (Instruction *NV = FoldOpIntoPhi(I))
3403 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003404 }
3405
Chris Lattnerbb74e222003-03-10 23:06:50 +00003406 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003407 if (X == Op1)
3408 return ReplaceInstUsesWith(I,
3409 ConstantIntegral::getAllOnesValue(I.getType()));
3410
Chris Lattnerbb74e222003-03-10 23:06:50 +00003411 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003412 if (X == Op0)
3413 return ReplaceInstUsesWith(I,
3414 ConstantIntegral::getAllOnesValue(I.getType()));
3415
Chris Lattnerdcd07922006-04-01 08:03:55 +00003416 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003417 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003418 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003419 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003420 I.swapOperands();
3421 std::swap(Op0, Op1);
3422 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003423 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003424 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003425 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003426 } else if (Op1I->getOpcode() == Instruction::Xor) {
3427 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3428 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3429 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3430 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003431 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3432 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3433 Op1I->swapOperands();
3434 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3435 I.swapOperands(); // Simplified below.
3436 std::swap(Op0, Op1);
3437 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003438 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003439
Chris Lattnerdcd07922006-04-01 08:03:55 +00003440 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003441 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003442 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003443 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003444 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003445 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3446 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003447 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003448 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003449 } else if (Op0I->getOpcode() == Instruction::Xor) {
3450 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3451 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3452 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3453 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003454 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3455 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3456 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003457 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3458 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003459 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3460 InsertNewInstBefore(N, I);
3461 return BinaryOperator::createAnd(N, Op1);
3462 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003463 }
3464
Chris Lattner3ac7c262003-08-13 20:16:26 +00003465 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3466 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3467 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3468 return R;
3469
Chris Lattner3af10532006-05-05 06:39:07 +00003470 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3471 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003472 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003473 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003474 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003475 // Only do this if the casts both really cause code to be generated.
3476 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3477 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003478 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3479 Op1C->getOperand(0),
3480 I.getName());
3481 InsertNewInstBefore(NewOp, I);
3482 return new CastInst(NewOp, I.getType());
3483 }
3484 }
3485
Chris Lattner113f4f42002-06-25 16:13:24 +00003486 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003487}
3488
Chris Lattner6862fbd2004-09-29 17:40:11 +00003489/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3490/// overflowed for this type.
3491static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3492 ConstantInt *In2) {
3493 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3494 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3495}
3496
3497static bool isPositive(ConstantInt *C) {
3498 return cast<ConstantSInt>(C)->getValue() >= 0;
3499}
3500
3501/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3502/// overflowed for this type.
3503static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3504 ConstantInt *In2) {
3505 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3506
3507 if (In1->getType()->isUnsigned())
3508 return cast<ConstantUInt>(Result)->getValue() <
3509 cast<ConstantUInt>(In1)->getValue();
3510 if (isPositive(In1) != isPositive(In2))
3511 return false;
3512 if (isPositive(In1))
3513 return cast<ConstantSInt>(Result)->getValue() <
3514 cast<ConstantSInt>(In1)->getValue();
3515 return cast<ConstantSInt>(Result)->getValue() >
3516 cast<ConstantSInt>(In1)->getValue();
3517}
3518
Chris Lattner0798af32005-01-13 20:14:25 +00003519/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3520/// code necessary to compute the offset from the base pointer (without adding
3521/// in the base pointer). Return the result as a signed integer of intptr size.
3522static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3523 TargetData &TD = IC.getTargetData();
3524 gep_type_iterator GTI = gep_type_begin(GEP);
3525 const Type *UIntPtrTy = TD.getIntPtrType();
3526 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3527 Value *Result = Constant::getNullValue(SIntPtrTy);
3528
3529 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003530 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003531
Chris Lattner0798af32005-01-13 20:14:25 +00003532 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3533 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003534 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003535 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3536 SIntPtrTy);
3537 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3538 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003539 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003540 Scale = ConstantExpr::getMul(OpC, Scale);
3541 if (Constant *RC = dyn_cast<Constant>(Result))
3542 Result = ConstantExpr::getAdd(RC, Scale);
3543 else {
3544 // Emit an add instruction.
3545 Result = IC.InsertNewInstBefore(
3546 BinaryOperator::createAdd(Result, Scale,
3547 GEP->getName()+".offs"), I);
3548 }
3549 }
3550 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003551 // Convert to correct type.
3552 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3553 Op->getName()+".c"), I);
3554 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003555 // We'll let instcombine(mul) convert this to a shl if possible.
3556 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3557 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003558
3559 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003560 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003561 GEP->getName()+".offs"), I);
3562 }
3563 }
3564 return Result;
3565}
3566
3567/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3568/// else. At this point we know that the GEP is on the LHS of the comparison.
3569Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3570 Instruction::BinaryOps Cond,
3571 Instruction &I) {
3572 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003573
3574 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3575 if (isa<PointerType>(CI->getOperand(0)->getType()))
3576 RHS = CI->getOperand(0);
3577
Chris Lattner0798af32005-01-13 20:14:25 +00003578 Value *PtrBase = GEPLHS->getOperand(0);
3579 if (PtrBase == RHS) {
3580 // As an optimization, we don't actually have to compute the actual value of
3581 // OFFSET if this is a seteq or setne comparison, just return whether each
3582 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003583 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3584 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003585 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3586 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003587 bool EmitIt = true;
3588 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3589 if (isa<UndefValue>(C)) // undef index -> undef.
3590 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3591 if (C->isNullValue())
3592 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003593 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3594 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003595 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003596 return ReplaceInstUsesWith(I, // No comparison is needed here.
3597 ConstantBool::get(Cond == Instruction::SetNE));
3598 }
3599
3600 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003601 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003602 new SetCondInst(Cond, GEPLHS->getOperand(i),
3603 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3604 if (InVal == 0)
3605 InVal = Comp;
3606 else {
3607 InVal = InsertNewInstBefore(InVal, I);
3608 InsertNewInstBefore(Comp, I);
3609 if (Cond == Instruction::SetNE) // True if any are unequal
3610 InVal = BinaryOperator::createOr(InVal, Comp);
3611 else // True if all are equal
3612 InVal = BinaryOperator::createAnd(InVal, Comp);
3613 }
3614 }
3615 }
3616
3617 if (InVal)
3618 return InVal;
3619 else
3620 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3621 ConstantBool::get(Cond == Instruction::SetEQ));
3622 }
Chris Lattner0798af32005-01-13 20:14:25 +00003623
3624 // Only lower this if the setcc is the only user of the GEP or if we expect
3625 // the result to fold to a constant!
3626 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3627 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3628 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3629 return new SetCondInst(Cond, Offset,
3630 Constant::getNullValue(Offset->getType()));
3631 }
3632 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003633 // If the base pointers are different, but the indices are the same, just
3634 // compare the base pointer.
3635 if (PtrBase != GEPRHS->getOperand(0)) {
3636 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003637 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003638 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003639 if (IndicesTheSame)
3640 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3641 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3642 IndicesTheSame = false;
3643 break;
3644 }
3645
3646 // If all indices are the same, just compare the base pointers.
3647 if (IndicesTheSame)
3648 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3649 GEPRHS->getOperand(0));
3650
3651 // Otherwise, the base pointers are different and the indices are
3652 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003653 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003654 }
Chris Lattner0798af32005-01-13 20:14:25 +00003655
Chris Lattner81e84172005-01-13 22:25:21 +00003656 // If one of the GEPs has all zero indices, recurse.
3657 bool AllZeros = true;
3658 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3659 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3660 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3661 AllZeros = false;
3662 break;
3663 }
3664 if (AllZeros)
3665 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3666 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003667
3668 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003669 AllZeros = true;
3670 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3671 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3672 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3673 AllZeros = false;
3674 break;
3675 }
3676 if (AllZeros)
3677 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3678
Chris Lattner4fa89822005-01-14 00:20:05 +00003679 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3680 // If the GEPs only differ by one index, compare it.
3681 unsigned NumDifferences = 0; // Keep track of # differences.
3682 unsigned DiffOperand = 0; // The operand that differs.
3683 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3684 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003685 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3686 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003687 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003688 NumDifferences = 2;
3689 break;
3690 } else {
3691 if (NumDifferences++) break;
3692 DiffOperand = i;
3693 }
3694 }
3695
3696 if (NumDifferences == 0) // SAME GEP?
3697 return ReplaceInstUsesWith(I, // No comparison is needed here.
3698 ConstantBool::get(Cond == Instruction::SetEQ));
3699 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003700 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3701 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003702
3703 // Convert the operands to signed values to make sure to perform a
3704 // signed comparison.
3705 const Type *NewTy = LHSV->getType()->getSignedVersion();
3706 if (LHSV->getType() != NewTy)
3707 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3708 LHSV->getName()), I);
3709 if (RHSV->getType() != NewTy)
3710 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3711 RHSV->getName()), I);
3712 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003713 }
3714 }
3715
Chris Lattner0798af32005-01-13 20:14:25 +00003716 // Only lower this if the setcc is the only user of the GEP or if we expect
3717 // the result to fold to a constant!
3718 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3719 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3720 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3721 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3722 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3723 return new SetCondInst(Cond, L, R);
3724 }
3725 }
3726 return 0;
3727}
3728
3729
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003730Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003731 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003732 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3733 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003734
3735 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003736 if (Op0 == Op1)
3737 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003738
Chris Lattner81a7a232004-10-16 18:11:37 +00003739 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3740 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3741
Chris Lattner15ff1e12004-11-14 07:33:16 +00003742 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3743 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003744 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3745 isa<ConstantPointerNull>(Op0)) &&
3746 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003747 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003748 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3749
3750 // setcc's with boolean values can always be turned into bitwise operations
3751 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003752 switch (I.getOpcode()) {
3753 default: assert(0 && "Invalid setcc instruction!");
3754 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003755 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003756 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003757 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003758 }
Chris Lattner4456da62004-08-11 00:50:51 +00003759 case Instruction::SetNE:
3760 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003761
Chris Lattner4456da62004-08-11 00:50:51 +00003762 case Instruction::SetGT:
3763 std::swap(Op0, Op1); // Change setgt -> setlt
3764 // FALL THROUGH
3765 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3766 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3767 InsertNewInstBefore(Not, I);
3768 return BinaryOperator::createAnd(Not, Op1);
3769 }
3770 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003771 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003772 // FALL THROUGH
3773 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3774 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3775 InsertNewInstBefore(Not, I);
3776 return BinaryOperator::createOr(Not, Op1);
3777 }
3778 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003779 }
3780
Chris Lattner2dd01742004-06-09 04:24:29 +00003781 // See if we are doing a comparison between a constant and an instruction that
3782 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003783 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003784 // Check to see if we are comparing against the minimum or maximum value...
3785 if (CI->isMinValue()) {
3786 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3787 return ReplaceInstUsesWith(I, ConstantBool::False);
3788 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3789 return ReplaceInstUsesWith(I, ConstantBool::True);
3790 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3791 return BinaryOperator::createSetEQ(Op0, Op1);
3792 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3793 return BinaryOperator::createSetNE(Op0, Op1);
3794
3795 } else if (CI->isMaxValue()) {
3796 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3797 return ReplaceInstUsesWith(I, ConstantBool::False);
3798 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3799 return ReplaceInstUsesWith(I, ConstantBool::True);
3800 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3801 return BinaryOperator::createSetEQ(Op0, Op1);
3802 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3803 return BinaryOperator::createSetNE(Op0, Op1);
3804
3805 // Comparing against a value really close to min or max?
3806 } else if (isMinValuePlusOne(CI)) {
3807 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3808 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3809 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3810 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3811
3812 } else if (isMaxValueMinusOne(CI)) {
3813 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3814 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3815 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3816 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3817 }
3818
3819 // If we still have a setle or setge instruction, turn it into the
3820 // appropriate setlt or setgt instruction. Since the border cases have
3821 // already been handled above, this requires little checking.
3822 //
3823 if (I.getOpcode() == Instruction::SetLE)
3824 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3825 if (I.getOpcode() == Instruction::SetGE)
3826 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3827
Chris Lattneree0f2802006-02-12 02:07:56 +00003828
3829 // See if we can fold the comparison based on bits known to be zero or one
3830 // in the input.
3831 uint64_t KnownZero, KnownOne;
3832 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3833 KnownZero, KnownOne, 0))
3834 return &I;
3835
3836 // Given the known and unknown bits, compute a range that the LHS could be
3837 // in.
3838 if (KnownOne | KnownZero) {
3839 if (Ty->isUnsigned()) { // Unsigned comparison.
3840 uint64_t Min, Max;
3841 uint64_t RHSVal = CI->getZExtValue();
3842 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3843 Min, Max);
3844 switch (I.getOpcode()) { // LE/GE have been folded already.
3845 default: assert(0 && "Unknown setcc opcode!");
3846 case Instruction::SetEQ:
3847 if (Max < RHSVal || Min > RHSVal)
3848 return ReplaceInstUsesWith(I, ConstantBool::False);
3849 break;
3850 case Instruction::SetNE:
3851 if (Max < RHSVal || Min > RHSVal)
3852 return ReplaceInstUsesWith(I, ConstantBool::True);
3853 break;
3854 case Instruction::SetLT:
3855 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3856 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3857 break;
3858 case Instruction::SetGT:
3859 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3860 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3861 break;
3862 }
3863 } else { // Signed comparison.
3864 int64_t Min, Max;
3865 int64_t RHSVal = CI->getSExtValue();
3866 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3867 Min, Max);
3868 switch (I.getOpcode()) { // LE/GE have been folded already.
3869 default: assert(0 && "Unknown setcc opcode!");
3870 case Instruction::SetEQ:
3871 if (Max < RHSVal || Min > RHSVal)
3872 return ReplaceInstUsesWith(I, ConstantBool::False);
3873 break;
3874 case Instruction::SetNE:
3875 if (Max < RHSVal || Min > RHSVal)
3876 return ReplaceInstUsesWith(I, ConstantBool::True);
3877 break;
3878 case Instruction::SetLT:
3879 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3880 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3881 break;
3882 case Instruction::SetGT:
3883 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3884 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3885 break;
3886 }
3887 }
3888 }
3889
3890
Chris Lattnere1e10e12004-05-25 06:32:08 +00003891 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003892 switch (LHSI->getOpcode()) {
3893 case Instruction::And:
3894 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3895 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00003896 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3897
3898 // If an operand is an AND of a truncating cast, we can widen the
3899 // and/compare to be the input width without changing the value
3900 // produced, eliminating a cast.
3901 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
3902 // We can do this transformation if either the AND constant does not
3903 // have its sign bit set or if it is an equality comparison.
3904 // Extending a relational comparison when we're checking the sign
3905 // bit would not work.
3906 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
3907 (I.isEquality() ||
3908 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
3909 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
3910 ConstantInt *NewCST;
3911 ConstantInt *NewCI;
3912 if (Cast->getOperand(0)->getType()->isSigned()) {
3913 NewCST = ConstantSInt::get(Cast->getOperand(0)->getType(),
3914 AndCST->getZExtValue());
3915 NewCI = ConstantSInt::get(Cast->getOperand(0)->getType(),
3916 CI->getZExtValue());
3917 } else {
3918 NewCST = ConstantUInt::get(Cast->getOperand(0)->getType(),
3919 AndCST->getZExtValue());
3920 NewCI = ConstantUInt::get(Cast->getOperand(0)->getType(),
3921 CI->getZExtValue());
3922 }
3923 Instruction *NewAnd =
3924 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
3925 LHSI->getName());
3926 InsertNewInstBefore(NewAnd, I);
3927 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
3928 }
3929 }
3930
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003931 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3932 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3933 // happens a LOT in code produced by the C front-end, for bitfield
3934 // access.
3935 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003936
3937 // Check to see if there is a noop-cast between the shift and the and.
3938 if (!Shift) {
3939 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3940 if (CI->getOperand(0)->getType()->isIntegral() &&
3941 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3942 CI->getType()->getPrimitiveSizeInBits())
3943 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3944 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003945
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003946 ConstantUInt *ShAmt;
3947 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003948 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3949 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003950
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003951 // We can fold this as long as we can't shift unknown bits
3952 // into the mask. This can only happen with signed shift
3953 // rights, as they sign-extend.
3954 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003955 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003956 if (!CanFold) {
3957 // To test for the bad case of the signed shr, see if any
3958 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003959 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3960 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3961
3962 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003963 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003964 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3965 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003966 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3967 CanFold = true;
3968 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003969
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003970 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003971 Constant *NewCst;
3972 if (Shift->getOpcode() == Instruction::Shl)
3973 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3974 else
3975 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003976
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003977 // Check to see if we are shifting out any of the bits being
3978 // compared.
3979 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3980 // If we shifted bits out, the fold is not going to work out.
3981 // As a special case, check to see if this means that the
3982 // result is always true or false now.
3983 if (I.getOpcode() == Instruction::SetEQ)
3984 return ReplaceInstUsesWith(I, ConstantBool::False);
3985 if (I.getOpcode() == Instruction::SetNE)
3986 return ReplaceInstUsesWith(I, ConstantBool::True);
3987 } else {
3988 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003989 Constant *NewAndCST;
3990 if (Shift->getOpcode() == Instruction::Shl)
3991 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3992 else
3993 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3994 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003995 if (AndTy == Ty)
3996 LHSI->setOperand(0, Shift->getOperand(0));
3997 else {
3998 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3999 *Shift);
4000 LHSI->setOperand(0, NewCast);
4001 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004002 WorkList.push_back(Shift); // Shift is dead.
4003 AddUsesToWorkList(I);
4004 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004005 }
4006 }
Chris Lattner35167c32004-06-09 07:59:58 +00004007 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004008
4009 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4010 // preferable because it allows the C<<Y expression to be hoisted out
4011 // of a loop if Y is invariant and X is not.
4012 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004013 I.isEquality() && !Shift->isArithmeticShift() &&
4014 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004015 // Compute C << Y.
4016 Value *NS;
4017 if (Shift->getOpcode() == Instruction::Shr) {
4018 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4019 "tmp");
4020 } else {
4021 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004022 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004023 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004024 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004025 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004026 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4027 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004028 }
4029 InsertNewInstBefore(cast<Instruction>(NS), I);
4030
4031 // If C's sign doesn't agree with the and, insert a cast now.
4032 if (NS->getType() != LHSI->getType())
4033 NS = InsertCastBefore(NS, LHSI->getType(), I);
4034
4035 Value *ShiftOp = Shift->getOperand(0);
4036 if (ShiftOp->getType() != LHSI->getType())
4037 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4038
4039 // Compute X & (C << Y).
4040 Instruction *NewAnd =
4041 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4042 InsertNewInstBefore(NewAnd, I);
4043
4044 I.setOperand(0, NewAnd);
4045 return &I;
4046 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004047 }
4048 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004049
Chris Lattner272d5ca2004-09-28 18:22:15 +00004050 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4051 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004052 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004053 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4054
4055 // Check that the shift amount is in range. If not, don't perform
4056 // undefined shifts. When the shift is visited it will be
4057 // simplified.
4058 if (ShAmt->getValue() >= TypeBits)
4059 break;
4060
Chris Lattner272d5ca2004-09-28 18:22:15 +00004061 // If we are comparing against bits always shifted out, the
4062 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004063 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004064 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4065 if (Comp != CI) {// Comparing against a bit that we know is zero.
4066 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4067 Constant *Cst = ConstantBool::get(IsSetNE);
4068 return ReplaceInstUsesWith(I, Cst);
4069 }
4070
4071 if (LHSI->hasOneUse()) {
4072 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004073 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004074 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4075
4076 Constant *Mask;
4077 if (CI->getType()->isUnsigned()) {
4078 Mask = ConstantUInt::get(CI->getType(), Val);
4079 } else if (ShAmtVal != 0) {
4080 Mask = ConstantSInt::get(CI->getType(), Val);
4081 } else {
4082 Mask = ConstantInt::getAllOnesValue(CI->getType());
4083 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004084
Chris Lattner272d5ca2004-09-28 18:22:15 +00004085 Instruction *AndI =
4086 BinaryOperator::createAnd(LHSI->getOperand(0),
4087 Mask, LHSI->getName()+".mask");
4088 Value *And = InsertNewInstBefore(AndI, I);
4089 return new SetCondInst(I.getOpcode(), And,
4090 ConstantExpr::getUShr(CI, ShAmt));
4091 }
4092 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004093 }
4094 break;
4095
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004096 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00004097 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004098 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004099 // Check that the shift amount is in range. If not, don't perform
4100 // undefined shifts. When the shift is visited it will be
4101 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004102 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00004103 if (ShAmt->getValue() >= TypeBits)
4104 break;
4105
Chris Lattner1023b872004-09-27 16:18:50 +00004106 // If we are comparing against bits always shifted out, the
4107 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004108 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004109 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004110
Chris Lattner1023b872004-09-27 16:18:50 +00004111 if (Comp != CI) {// Comparing against a bit that we know is zero.
4112 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4113 Constant *Cst = ConstantBool::get(IsSetNE);
4114 return ReplaceInstUsesWith(I, Cst);
4115 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004116
Chris Lattner1023b872004-09-27 16:18:50 +00004117 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004118 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004119
Chris Lattner1023b872004-09-27 16:18:50 +00004120 // Otherwise strength reduce the shift into an and.
4121 uint64_t Val = ~0ULL; // All ones.
4122 Val <<= ShAmtVal; // Shift over to the right spot.
4123
4124 Constant *Mask;
4125 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004126 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00004127 Mask = ConstantUInt::get(CI->getType(), Val);
4128 } else {
4129 Mask = ConstantSInt::get(CI->getType(), Val);
4130 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004131
Chris Lattner1023b872004-09-27 16:18:50 +00004132 Instruction *AndI =
4133 BinaryOperator::createAnd(LHSI->getOperand(0),
4134 Mask, LHSI->getName()+".mask");
4135 Value *And = InsertNewInstBefore(AndI, I);
4136 return new SetCondInst(I.getOpcode(), And,
4137 ConstantExpr::getShl(CI, ShAmt));
4138 }
Chris Lattner1023b872004-09-27 16:18:50 +00004139 }
4140 }
4141 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004142
Chris Lattner6862fbd2004-09-29 17:40:11 +00004143 case Instruction::Div:
4144 // Fold: (div X, C1) op C2 -> range check
4145 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4146 // Fold this div into the comparison, producing a range check.
4147 // Determine, based on the divide type, what the range is being
4148 // checked. If there is an overflow on the low or high side, remember
4149 // it, otherwise compute the range [low, hi) bounding the new value.
4150 bool LoOverflow = false, HiOverflow = 0;
4151 ConstantInt *LoBound = 0, *HiBound = 0;
4152
4153 ConstantInt *Prod;
4154 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4155
Chris Lattnera92af962004-10-11 19:40:04 +00004156 Instruction::BinaryOps Opcode = I.getOpcode();
4157
Chris Lattner6862fbd2004-09-29 17:40:11 +00004158 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4159 } else if (LHSI->getType()->isUnsigned()) { // udiv
4160 LoBound = Prod;
4161 LoOverflow = ProdOV;
4162 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4163 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4164 if (CI->isNullValue()) { // (X / pos) op 0
4165 // Can't overflow.
4166 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4167 HiBound = DivRHS;
4168 } else if (isPositive(CI)) { // (X / pos) op pos
4169 LoBound = Prod;
4170 LoOverflow = ProdOV;
4171 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4172 } else { // (X / pos) op neg
4173 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4174 LoOverflow = AddWithOverflow(LoBound, Prod,
4175 cast<ConstantInt>(DivRHSH));
4176 HiBound = Prod;
4177 HiOverflow = ProdOV;
4178 }
4179 } else { // Divisor is < 0.
4180 if (CI->isNullValue()) { // (X / neg) op 0
4181 LoBound = AddOne(DivRHS);
4182 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004183 if (HiBound == DivRHS)
4184 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004185 } else if (isPositive(CI)) { // (X / neg) op pos
4186 HiOverflow = LoOverflow = ProdOV;
4187 if (!LoOverflow)
4188 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4189 HiBound = AddOne(Prod);
4190 } else { // (X / neg) op neg
4191 LoBound = Prod;
4192 LoOverflow = HiOverflow = ProdOV;
4193 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4194 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004195
Chris Lattnera92af962004-10-11 19:40:04 +00004196 // Dividing by a negate swaps the condition.
4197 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004198 }
4199
4200 if (LoBound) {
4201 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004202 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004203 default: assert(0 && "Unhandled setcc opcode!");
4204 case Instruction::SetEQ:
4205 if (LoOverflow && HiOverflow)
4206 return ReplaceInstUsesWith(I, ConstantBool::False);
4207 else if (HiOverflow)
4208 return new SetCondInst(Instruction::SetGE, X, LoBound);
4209 else if (LoOverflow)
4210 return new SetCondInst(Instruction::SetLT, X, HiBound);
4211 else
4212 return InsertRangeTest(X, LoBound, HiBound, true, I);
4213 case Instruction::SetNE:
4214 if (LoOverflow && HiOverflow)
4215 return ReplaceInstUsesWith(I, ConstantBool::True);
4216 else if (HiOverflow)
4217 return new SetCondInst(Instruction::SetLT, X, LoBound);
4218 else if (LoOverflow)
4219 return new SetCondInst(Instruction::SetGE, X, HiBound);
4220 else
4221 return InsertRangeTest(X, LoBound, HiBound, false, I);
4222 case Instruction::SetLT:
4223 if (LoOverflow)
4224 return ReplaceInstUsesWith(I, ConstantBool::False);
4225 return new SetCondInst(Instruction::SetLT, X, LoBound);
4226 case Instruction::SetGT:
4227 if (HiOverflow)
4228 return ReplaceInstUsesWith(I, ConstantBool::False);
4229 return new SetCondInst(Instruction::SetGE, X, HiBound);
4230 }
4231 }
4232 }
4233 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004234 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004235
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004236 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004237 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004238 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4239
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004240 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004241 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4243 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004244 case Instruction::Rem:
4245 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4246 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4247 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004248 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4249 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4250 if (isPowerOf2_64(V)) {
4251 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004252 const Type *UTy = BO->getType()->getUnsignedVersion();
4253 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4254 UTy, "tmp"), I);
4255 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4256 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4257 RHSCst, BO->getName()), I);
4258 return BinaryOperator::create(I.getOpcode(), NewRem,
4259 Constant::getNullValue(UTy));
4260 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004261 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004262 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004263
Chris Lattnerc992add2003-08-13 05:33:12 +00004264 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004265 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4266 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004267 if (BO->hasOneUse())
4268 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4269 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004270 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004271 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4272 // efficiently invertible, or if the add has just this one use.
4273 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004274
Chris Lattnerc992add2003-08-13 05:33:12 +00004275 if (Value *NegVal = dyn_castNegVal(BOp1))
4276 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4277 else if (Value *NegVal = dyn_castNegVal(BOp0))
4278 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004279 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004280 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4281 BO->setName("");
4282 InsertNewInstBefore(Neg, I);
4283 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4284 }
4285 }
4286 break;
4287 case Instruction::Xor:
4288 // For the xor case, we can xor two constants together, eliminating
4289 // the explicit xor.
4290 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4291 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004292 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004293
4294 // FALLTHROUGH
4295 case Instruction::Sub:
4296 // Replace (([sub|xor] A, B) != 0) with (A != B)
4297 if (CI->isNullValue())
4298 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4299 BO->getOperand(1));
4300 break;
4301
4302 case Instruction::Or:
4303 // If bits are being or'd in that are not present in the constant we
4304 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004305 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004306 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004307 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004308 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004309 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004310 break;
4311
4312 case Instruction::And:
4313 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004314 // If bits are being compared against that are and'd out, then the
4315 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004316 if (!ConstantExpr::getAnd(CI,
4317 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004318 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004319
Chris Lattner35167c32004-06-09 07:59:58 +00004320 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004321 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004322 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4323 Instruction::SetNE, Op0,
4324 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004325
Chris Lattnerc992add2003-08-13 05:33:12 +00004326 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4327 // to be a signed value as appropriate.
4328 if (isSignBit(BOC)) {
4329 Value *X = BO->getOperand(0);
4330 // If 'X' is not signed, insert a cast now...
4331 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004332 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004333 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004334 }
4335 return new SetCondInst(isSetNE ? Instruction::SetLT :
4336 Instruction::SetGE, X,
4337 Constant::getNullValue(X->getType()));
4338 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004339
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004340 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004341 if (CI->isNullValue() && isHighOnes(BOC)) {
4342 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004343 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004344
4345 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004346 if (NegX->getType()->isSigned()) {
4347 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4348 X = InsertCastBefore(X, DestTy, I);
4349 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004350 }
4351
4352 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004353 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004354 }
4355
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004356 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004357 default: break;
4358 }
4359 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004360 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004361 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004362 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4363 Value *CastOp = Cast->getOperand(0);
4364 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004365 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004366 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004367 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004368 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004369 "Source and destination signednesses should differ!");
4370 if (Cast->getType()->isSigned()) {
4371 // If this is a signed comparison, check for comparisons in the
4372 // vicinity of zero.
4373 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4374 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004375 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004376 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004377 else if (I.getOpcode() == Instruction::SetGT &&
4378 cast<ConstantSInt>(CI)->getValue() == -1)
4379 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004380 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004381 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004382 } else {
4383 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4384 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004385 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004386 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004387 return BinaryOperator::createSetGT(CastOp,
4388 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004389 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004390 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004391 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004392 return BinaryOperator::createSetLT(CastOp,
4393 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004394 }
4395 }
4396 }
Chris Lattnere967b342003-06-04 05:10:11 +00004397 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004398 }
4399
Chris Lattner77c32c32005-04-23 15:31:55 +00004400 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4401 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4402 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4403 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004404 case Instruction::GetElementPtr:
4405 if (RHSC->isNullValue()) {
4406 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4407 bool isAllZeros = true;
4408 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4409 if (!isa<Constant>(LHSI->getOperand(i)) ||
4410 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4411 isAllZeros = false;
4412 break;
4413 }
4414 if (isAllZeros)
4415 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4416 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4417 }
4418 break;
4419
Chris Lattner77c32c32005-04-23 15:31:55 +00004420 case Instruction::PHI:
4421 if (Instruction *NV = FoldOpIntoPhi(I))
4422 return NV;
4423 break;
4424 case Instruction::Select:
4425 // If either operand of the select is a constant, we can fold the
4426 // comparison into the select arms, which will cause one to be
4427 // constant folded and the select turned into a bitwise or.
4428 Value *Op1 = 0, *Op2 = 0;
4429 if (LHSI->hasOneUse()) {
4430 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4431 // Fold the known value into the constant operand.
4432 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4433 // Insert a new SetCC of the other select operand.
4434 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4435 LHSI->getOperand(2), RHSC,
4436 I.getName()), I);
4437 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4438 // Fold the known value into the constant operand.
4439 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4440 // Insert a new SetCC of the other select operand.
4441 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4442 LHSI->getOperand(1), RHSC,
4443 I.getName()), I);
4444 }
4445 }
Jeff Cohen82639852005-04-23 21:38:35 +00004446
Chris Lattner77c32c32005-04-23 15:31:55 +00004447 if (Op1)
4448 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4449 break;
4450 }
4451 }
4452
Chris Lattner0798af32005-01-13 20:14:25 +00004453 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4454 if (User *GEP = dyn_castGetElementPtr(Op0))
4455 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4456 return NI;
4457 if (User *GEP = dyn_castGetElementPtr(Op1))
4458 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4459 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4460 return NI;
4461
Chris Lattner16930792003-11-03 04:25:02 +00004462 // Test to see if the operands of the setcc are casted versions of other
4463 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004464 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4465 Value *CastOp0 = CI->getOperand(0);
4466 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004467 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004468 // We keep moving the cast from the left operand over to the right
4469 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004470 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004471
Chris Lattner16930792003-11-03 04:25:02 +00004472 // If operand #1 is a cast instruction, see if we can eliminate it as
4473 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004474 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4475 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004476 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004477 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004478
Chris Lattner16930792003-11-03 04:25:02 +00004479 // If Op1 is a constant, we can fold the cast into the constant.
4480 if (Op1->getType() != Op0->getType())
4481 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4482 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4483 } else {
4484 // Otherwise, cast the RHS right before the setcc
4485 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4486 InsertNewInstBefore(cast<Instruction>(Op1), I);
4487 }
4488 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4489 }
4490
Chris Lattner6444c372003-11-03 05:17:03 +00004491 // Handle the special case of: setcc (cast bool to X), <cst>
4492 // This comes up when you have code like
4493 // int X = A < B;
4494 // if (X) ...
4495 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004496 // with a constant or another cast from the same type.
4497 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4498 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4499 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004500 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004501
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004502 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004503 Value *A, *B;
4504 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4505 (A == Op1 || B == Op1)) {
4506 // (A^B) == A -> B == 0
4507 Value *OtherVal = A == Op1 ? B : A;
4508 return BinaryOperator::create(I.getOpcode(), OtherVal,
4509 Constant::getNullValue(A->getType()));
4510 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4511 (A == Op0 || B == Op0)) {
4512 // A == (A^B) -> B == 0
4513 Value *OtherVal = A == Op0 ? B : A;
4514 return BinaryOperator::create(I.getOpcode(), OtherVal,
4515 Constant::getNullValue(A->getType()));
4516 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4517 // (A-B) == A -> B == 0
4518 return BinaryOperator::create(I.getOpcode(), B,
4519 Constant::getNullValue(B->getType()));
4520 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4521 // A == (A-B) -> B == 0
4522 return BinaryOperator::create(I.getOpcode(), B,
4523 Constant::getNullValue(B->getType()));
4524 }
4525 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004526 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004527}
4528
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004529// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4530// We only handle extending casts so far.
4531//
4532Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4533 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4534 const Type *SrcTy = LHSCIOp->getType();
4535 const Type *DestTy = SCI.getOperand(0)->getType();
4536 Value *RHSCIOp;
4537
4538 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004539 return 0;
4540
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004541 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4542 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4543 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4544
4545 // Is this a sign or zero extension?
4546 bool isSignSrc = SrcTy->isSigned();
4547 bool isSignDest = DestTy->isSigned();
4548
4549 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4550 // Not an extension from the same type?
4551 RHSCIOp = CI->getOperand(0);
4552 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4553 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4554 // Compute the constant that would happen if we truncated to SrcTy then
4555 // reextended to DestTy.
4556 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4557
4558 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4559 RHSCIOp = Res;
4560 } else {
4561 // If the value cannot be represented in the shorter type, we cannot emit
4562 // a simple comparison.
4563 if (SCI.getOpcode() == Instruction::SetEQ)
4564 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4565 if (SCI.getOpcode() == Instruction::SetNE)
4566 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4567
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004568 // Evaluate the comparison for LT.
4569 Value *Result;
4570 if (DestTy->isSigned()) {
4571 // We're performing a signed comparison.
4572 if (isSignSrc) {
4573 // Signed extend and signed comparison.
4574 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4575 Result = ConstantBool::False;
4576 else
4577 Result = ConstantBool::True; // X < (large) --> true
4578 } else {
4579 // Unsigned extend and signed comparison.
4580 if (cast<ConstantSInt>(CI)->getValue() < 0)
4581 Result = ConstantBool::False;
4582 else
4583 Result = ConstantBool::True;
4584 }
4585 } else {
4586 // We're performing an unsigned comparison.
4587 if (!isSignSrc) {
4588 // Unsigned extend & compare -> always true.
4589 Result = ConstantBool::True;
4590 } else {
4591 // We're performing an unsigned comp with a sign extended value.
4592 // This is true if the input is >= 0. [aka >s -1]
4593 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4594 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4595 NegOne, SCI.getName()), SCI);
4596 }
Reid Spencer279fa252004-11-28 21:31:15 +00004597 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004598
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004599 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004600 if (SCI.getOpcode() == Instruction::SetLT) {
4601 return ReplaceInstUsesWith(SCI, Result);
4602 } else {
4603 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4604 if (Constant *CI = dyn_cast<Constant>(Result))
4605 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4606 else
4607 return BinaryOperator::createNot(Result);
4608 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004609 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004610 } else {
4611 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004612 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004613
Chris Lattner252a8452005-06-16 03:00:08 +00004614 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004615 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4616}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004617
Chris Lattnere8d6c602003-03-10 19:16:08 +00004618Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004619 assert(I.getOperand(1)->getType() == Type::UByteTy);
4620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004621 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004622
4623 // shl X, 0 == X and shr X, 0 == X
4624 // shl 0, X == 0 and shr 0, X == 0
4625 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004626 Op0 == Constant::getNullValue(Op0->getType()))
4627 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004628
Chris Lattner81a7a232004-10-16 18:11:37 +00004629 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4630 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004631 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004632 else // undef << X -> 0 AND undef >>u X -> 0
4633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4634 }
4635 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004636 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004637 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4638 else
4639 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4640 }
4641
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004642 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4643 if (!isLeftShift)
4644 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4645 if (CSI->isAllOnesValue())
4646 return ReplaceInstUsesWith(I, CSI);
4647
Chris Lattner183b3362004-04-09 19:05:30 +00004648 // Try to fold constant and into select arguments.
4649 if (isa<Constant>(Op0))
4650 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004651 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004652 return R;
4653
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004654 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004655 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004656 if (MaskedValueIsZero(Op0,
4657 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004658 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4659 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4660 I.getName()), I);
4661 return new CastInst(V, I.getType());
4662 }
4663 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004664
Chris Lattner14553932006-01-06 07:12:35 +00004665 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4666 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4667 return Res;
4668 return 0;
4669}
4670
4671Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4672 ShiftInst &I) {
4673 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004674 bool isSignedShift = Op0->getType()->isSigned();
4675 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004676
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004677 // See if we can simplify any instructions used by the instruction whose sole
4678 // purpose is to compute bits we don't care about.
4679 uint64_t KnownZero, KnownOne;
4680 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4681 KnownZero, KnownOne))
4682 return &I;
4683
Chris Lattner14553932006-01-06 07:12:35 +00004684 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4685 // of a signed value.
4686 //
4687 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4688 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004689 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004690 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4691 else {
4692 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4693 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004694 }
Chris Lattner14553932006-01-06 07:12:35 +00004695 }
4696
4697 // ((X*C1) << C2) == (X * (C1 << C2))
4698 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4699 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4700 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4701 return BinaryOperator::createMul(BO->getOperand(0),
4702 ConstantExpr::getShl(BOOp, Op1));
4703
4704 // Try to fold constant and into select arguments.
4705 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4706 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4707 return R;
4708 if (isa<PHINode>(Op0))
4709 if (Instruction *NV = FoldOpIntoPhi(I))
4710 return NV;
4711
4712 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004713 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4714 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4715 Value *V1, *V2;
4716 ConstantInt *CC;
4717 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004718 default: break;
4719 case Instruction::Add:
4720 case Instruction::And:
4721 case Instruction::Or:
4722 case Instruction::Xor:
4723 // These operators commute.
4724 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004725 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4726 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004727 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004728 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004729 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004730 Op0BO->getName());
4731 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004732 Instruction *X =
4733 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4734 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004735 InsertNewInstBefore(X, I); // (X + (Y << C))
4736 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004737 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004738 return BinaryOperator::createAnd(X, C2);
4739 }
Chris Lattner14553932006-01-06 07:12:35 +00004740
Chris Lattner797dee72005-09-18 06:30:59 +00004741 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4742 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4743 match(Op0BO->getOperand(1),
4744 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004745 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004746 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004747 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004748 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004749 Op0BO->getName());
4750 InsertNewInstBefore(YS, I); // (Y << C)
4751 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004752 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004753 V1->getName()+".mask");
4754 InsertNewInstBefore(XM, I); // X & (CC << C)
4755
4756 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4757 }
Chris Lattner14553932006-01-06 07:12:35 +00004758
Chris Lattner797dee72005-09-18 06:30:59 +00004759 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004760 case Instruction::Sub:
4761 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004762 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4763 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004764 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004765 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004766 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004767 Op0BO->getName());
4768 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004769 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004770 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004771 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004772 InsertNewInstBefore(X, I); // (X + (Y << C))
4773 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004774 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004775 return BinaryOperator::createAnd(X, C2);
4776 }
Chris Lattner14553932006-01-06 07:12:35 +00004777
Chris Lattner1df0e982006-05-31 21:14:00 +00004778 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004779 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4780 match(Op0BO->getOperand(0),
4781 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004782 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004783 cast<BinaryOperator>(Op0BO->getOperand(0))
4784 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004785 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004786 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004787 Op0BO->getName());
4788 InsertNewInstBefore(YS, I); // (Y << C)
4789 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004790 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004791 V1->getName()+".mask");
4792 InsertNewInstBefore(XM, I); // X & (CC << C)
4793
Chris Lattner1df0e982006-05-31 21:14:00 +00004794 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004795 }
Chris Lattner14553932006-01-06 07:12:35 +00004796
Chris Lattner27cb9db2005-09-18 05:12:10 +00004797 break;
Chris Lattner14553932006-01-06 07:12:35 +00004798 }
4799
4800
4801 // If the operand is an bitwise operator with a constant RHS, and the
4802 // shift is the only use, we can pull it out of the shift.
4803 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4804 bool isValid = true; // Valid only for And, Or, Xor
4805 bool highBitSet = false; // Transform if high bit of constant set?
4806
4807 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004808 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004809 case Instruction::Add:
4810 isValid = isLeftShift;
4811 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004812 case Instruction::Or:
4813 case Instruction::Xor:
4814 highBitSet = false;
4815 break;
4816 case Instruction::And:
4817 highBitSet = true;
4818 break;
Chris Lattner14553932006-01-06 07:12:35 +00004819 }
4820
4821 // If this is a signed shift right, and the high bit is modified
4822 // by the logical operation, do not perform the transformation.
4823 // The highBitSet boolean indicates the value of the high bit of
4824 // the constant which would cause it to be modified for this
4825 // operation.
4826 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004827 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004828 uint64_t Val = Op0C->getRawValue();
4829 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4830 }
4831
4832 if (isValid) {
4833 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4834
4835 Instruction *NewShift =
4836 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4837 Op0BO->getName());
4838 Op0BO->setName("");
4839 InsertNewInstBefore(NewShift, I);
4840
4841 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4842 NewRHS);
4843 }
4844 }
4845 }
4846 }
4847
Chris Lattnereb372a02006-01-06 07:52:12 +00004848 // Find out if this is a shift of a shift by a constant.
4849 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004850 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004851 ShiftOp = Op0SI;
4852 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4853 // If this is a noop-integer case of a shift instruction, use the shift.
4854 if (CI->getOperand(0)->getType()->isInteger() &&
4855 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4856 CI->getType()->getPrimitiveSizeInBits() &&
4857 isa<ShiftInst>(CI->getOperand(0))) {
4858 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4859 }
4860 }
4861
4862 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4863 // Find the operands and properties of the input shift. Note that the
4864 // signedness of the input shift may differ from the current shift if there
4865 // is a noop cast between the two.
4866 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4867 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004868 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004869
4870 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4871
4872 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4873 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4874
4875 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4876 if (isLeftShift == isShiftOfLeftShift) {
4877 // Do not fold these shifts if the first one is signed and the second one
4878 // is unsigned and this is a right shift. Further, don't do any folding
4879 // on them.
4880 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4881 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004882
Chris Lattnereb372a02006-01-06 07:52:12 +00004883 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4884 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4885 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004886
Chris Lattnereb372a02006-01-06 07:52:12 +00004887 Value *Op = ShiftOp->getOperand(0);
4888 if (isShiftOfSignedShift != isSignedShift)
4889 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4890 return new ShiftInst(I.getOpcode(), Op,
4891 ConstantUInt::get(Type::UByteTy, Amt));
4892 }
4893
4894 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4895 // signed types, we can only support the (A >> c1) << c2 configuration,
4896 // because it can not turn an arbitrary bit of A into a sign bit.
4897 if (isUnsignedShift || isLeftShift) {
4898 // Calculate bitmask for what gets shifted off the edge.
4899 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4900 if (isLeftShift)
4901 C = ConstantExpr::getShl(C, ShiftAmt1C);
4902 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004903 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004904
4905 Value *Op = ShiftOp->getOperand(0);
4906 if (isShiftOfSignedShift != isSignedShift)
4907 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4908
4909 Instruction *Mask =
4910 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4911 InsertNewInstBefore(Mask, I);
4912
4913 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004914 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004915 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004916 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004917 return new ShiftInst(I.getOpcode(), Mask,
4918 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004919 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4920 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4921 // Make sure to emit an unsigned shift right, not a signed one.
4922 Mask = InsertNewInstBefore(new CastInst(Mask,
4923 Mask->getType()->getUnsignedVersion(),
4924 Op->getName()), I);
4925 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004926 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004927 InsertNewInstBefore(Mask, I);
4928 return new CastInst(Mask, I.getType());
4929 } else {
4930 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4931 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4932 }
4933 } else {
4934 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4935 Op = InsertNewInstBefore(new CastInst(Mask,
4936 I.getType()->getSignedVersion(),
4937 Mask->getName()), I);
4938 Instruction *Shift =
4939 new ShiftInst(ShiftOp->getOpcode(), Op,
4940 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4941 InsertNewInstBefore(Shift, I);
4942
4943 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4944 C = ConstantExpr::getShl(C, Op1);
4945 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4946 InsertNewInstBefore(Mask, I);
4947 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004948 }
4949 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004950 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004951 // this case, C1 == C2 and C1 is 8, 16, or 32.
4952 if (ShiftAmt1 == ShiftAmt2) {
4953 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004954 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004955 case 8 : SExtType = Type::SByteTy; break;
4956 case 16: SExtType = Type::ShortTy; break;
4957 case 32: SExtType = Type::IntTy; break;
4958 }
4959
4960 if (SExtType) {
4961 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4962 SExtType, "sext");
4963 InsertNewInstBefore(NewTrunc, I);
4964 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004965 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004966 }
Chris Lattner86102b82005-01-01 16:22:27 +00004967 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004968 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004969 return 0;
4970}
4971
Chris Lattner48a44f72002-05-02 17:06:02 +00004972
Chris Lattner8f663e82005-10-29 04:36:15 +00004973/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4974/// expression. If so, decompose it, returning some value X, such that Val is
4975/// X*Scale+Offset.
4976///
4977static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4978 unsigned &Offset) {
4979 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4980 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4981 Offset = CI->getValue();
4982 Scale = 1;
4983 return ConstantUInt::get(Type::UIntTy, 0);
4984 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4985 if (I->getNumOperands() == 2) {
4986 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4987 if (I->getOpcode() == Instruction::Shl) {
4988 // This is a value scaled by '1 << the shift amt'.
4989 Scale = 1U << CUI->getValue();
4990 Offset = 0;
4991 return I->getOperand(0);
4992 } else if (I->getOpcode() == Instruction::Mul) {
4993 // This value is scaled by 'CUI'.
4994 Scale = CUI->getValue();
4995 Offset = 0;
4996 return I->getOperand(0);
4997 } else if (I->getOpcode() == Instruction::Add) {
4998 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4999 // divisible by C2.
5000 unsigned SubScale;
5001 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
5002 Offset);
5003 Offset += CUI->getValue();
5004 if (SubScale > 1 && (Offset % SubScale == 0)) {
5005 Scale = SubScale;
5006 return SubVal;
5007 }
5008 }
5009 }
5010 }
5011 }
5012
5013 // Otherwise, we can't look past this.
5014 Scale = 1;
5015 Offset = 0;
5016 return Val;
5017}
5018
5019
Chris Lattner216be912005-10-24 06:03:58 +00005020/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5021/// try to eliminate the cast by moving the type information into the alloc.
5022Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5023 AllocationInst &AI) {
5024 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005025 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005026
Chris Lattnerac87beb2005-10-24 06:22:12 +00005027 // Remove any uses of AI that are dead.
5028 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5029 std::vector<Instruction*> DeadUsers;
5030 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5031 Instruction *User = cast<Instruction>(*UI++);
5032 if (isInstructionTriviallyDead(User)) {
5033 while (UI != E && *UI == User)
5034 ++UI; // If this instruction uses AI more than once, don't break UI.
5035
5036 // Add operands to the worklist.
5037 AddUsesToWorkList(*User);
5038 ++NumDeadInst;
5039 DEBUG(std::cerr << "IC: DCE: " << *User);
5040
5041 User->eraseFromParent();
5042 removeFromWorkList(User);
5043 }
5044 }
5045
Chris Lattner216be912005-10-24 06:03:58 +00005046 // Get the type really allocated and the type casted to.
5047 const Type *AllocElTy = AI.getAllocatedType();
5048 const Type *CastElTy = PTy->getElementType();
5049 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005050
5051 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
5052 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
5053 if (CastElTyAlign < AllocElTyAlign) return 0;
5054
Chris Lattner46705b22005-10-24 06:35:18 +00005055 // If the allocation has multiple uses, only promote it if we are strictly
5056 // increasing the alignment of the resultant allocation. If we keep it the
5057 // same, we open the door to infinite loops of various kinds.
5058 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5059
Chris Lattner216be912005-10-24 06:03:58 +00005060 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5061 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005062 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005063
Chris Lattner8270c332005-10-29 03:19:53 +00005064 // See if we can satisfy the modulus by pulling a scale out of the array
5065 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005066 unsigned ArraySizeScale, ArrayOffset;
5067 Value *NumElements = // See if the array size is a decomposable linear expr.
5068 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5069
Chris Lattner8270c332005-10-29 03:19:53 +00005070 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5071 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005072 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5073 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005074
Chris Lattner8270c332005-10-29 03:19:53 +00005075 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5076 Value *Amt = 0;
5077 if (Scale == 1) {
5078 Amt = NumElements;
5079 } else {
5080 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5081 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5082 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5083 else if (Scale != 1) {
5084 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5085 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005086 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005087 }
5088
Chris Lattner8f663e82005-10-29 04:36:15 +00005089 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5090 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5091 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5092 Amt = InsertNewInstBefore(Tmp, AI);
5093 }
5094
Chris Lattner216be912005-10-24 06:03:58 +00005095 std::string Name = AI.getName(); AI.setName("");
5096 AllocationInst *New;
5097 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005098 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005099 else
Nate Begeman848622f2005-11-05 09:21:28 +00005100 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005101 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005102
5103 // If the allocation has multiple uses, insert a cast and change all things
5104 // that used it to use the new cast. This will also hack on CI, but it will
5105 // die soon.
5106 if (!AI.hasOneUse()) {
5107 AddUsesToWorkList(AI);
5108 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5109 InsertNewInstBefore(NewCast, AI);
5110 AI.replaceAllUsesWith(NewCast);
5111 }
Chris Lattner216be912005-10-24 06:03:58 +00005112 return ReplaceInstUsesWith(CI, New);
5113}
5114
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005115/// CanEvaluateInDifferentType - Return true if we can take the specified value
5116/// and return it without inserting any new casts. This is used by code that
5117/// tries to decide whether promoting or shrinking integer operations to wider
5118/// or smaller types will allow us to eliminate a truncate or extend.
5119static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5120 int &NumCastsRemoved) {
5121 if (isa<Constant>(V)) return true;
5122
5123 Instruction *I = dyn_cast<Instruction>(V);
5124 if (!I || !I->hasOneUse()) return false;
5125
5126 switch (I->getOpcode()) {
5127 case Instruction::And:
5128 case Instruction::Or:
5129 case Instruction::Xor:
5130 // These operators can all arbitrarily be extended or truncated.
5131 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5132 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5133 case Instruction::Cast:
5134 // If this is a cast from the destination type, we can trivially eliminate
5135 // it, and this will remove a cast overall.
5136 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005137 // If the first operand is itself a cast, and is eliminable, do not count
5138 // this as an eliminable cast. We would prefer to eliminate those two
5139 // casts first.
5140 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5141 return true;
5142
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005143 ++NumCastsRemoved;
5144 return true;
5145 }
5146 // TODO: Can handle more cases here.
5147 break;
5148 }
5149
5150 return false;
5151}
5152
5153/// EvaluateInDifferentType - Given an expression that
5154/// CanEvaluateInDifferentType returns true for, actually insert the code to
5155/// evaluate the expression.
5156Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5157 if (Constant *C = dyn_cast<Constant>(V))
5158 return ConstantExpr::getCast(C, Ty);
5159
5160 // Otherwise, it must be an instruction.
5161 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005162 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005163 switch (I->getOpcode()) {
5164 case Instruction::And:
5165 case Instruction::Or:
5166 case Instruction::Xor: {
5167 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5168 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5169 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5170 LHS, RHS, I->getName());
5171 break;
5172 }
5173 case Instruction::Cast:
5174 // If this is a cast from the destination type, return the input.
5175 if (I->getOperand(0)->getType() == Ty)
5176 return I->getOperand(0);
5177
5178 // TODO: Can handle more cases here.
5179 assert(0 && "Unreachable!");
5180 break;
5181 }
5182
5183 return InsertNewInstBefore(Res, *I);
5184}
5185
Chris Lattner216be912005-10-24 06:03:58 +00005186
Chris Lattner48a44f72002-05-02 17:06:02 +00005187// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005188//
Chris Lattner113f4f42002-06-25 16:13:24 +00005189Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005190 Value *Src = CI.getOperand(0);
5191
Chris Lattner48a44f72002-05-02 17:06:02 +00005192 // If the user is casting a value to the same type, eliminate this cast
5193 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005194 if (CI.getType() == Src->getType())
5195 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005196
Chris Lattner81a7a232004-10-16 18:11:37 +00005197 if (isa<UndefValue>(Src)) // cast undef -> undef
5198 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5199
Chris Lattner48a44f72002-05-02 17:06:02 +00005200 // If casting the result of another cast instruction, try to eliminate this
5201 // one!
5202 //
Chris Lattner86102b82005-01-01 16:22:27 +00005203 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5204 Value *A = CSrc->getOperand(0);
5205 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5206 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005207 // This instruction now refers directly to the cast's src operand. This
5208 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005209 CI.setOperand(0, CSrc->getOperand(0));
5210 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005211 }
5212
Chris Lattner650b6da2002-08-02 20:00:25 +00005213 // If this is an A->B->A cast, and we are dealing with integral types, try
5214 // to convert this into a logical 'and' instruction.
5215 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005216 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005217 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005218 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005219 CSrc->getType()->getPrimitiveSizeInBits() <
5220 CI.getType()->getPrimitiveSizeInBits()&&
5221 A->getType()->getPrimitiveSizeInBits() ==
5222 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005223 assert(CSrc->getType() != Type::ULongTy &&
5224 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005225 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005226 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5227 AndValue);
5228 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5229 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5230 if (And->getType() != CI.getType()) {
5231 And->setName(CSrc->getName()+".mask");
5232 InsertNewInstBefore(And, CI);
5233 And = new CastInst(And, CI.getType());
5234 }
5235 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005236 }
5237 }
Chris Lattner2590e512006-02-07 06:56:34 +00005238
Chris Lattner03841652004-05-25 04:29:21 +00005239 // If this is a cast to bool, turn it into the appropriate setne instruction.
5240 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005241 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005242 Constant::getNullValue(CI.getOperand(0)->getType()));
5243
Chris Lattner2590e512006-02-07 06:56:34 +00005244 // See if we can simplify any instructions used by the LHS whose sole
5245 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005246 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5247 uint64_t KnownZero, KnownOne;
5248 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5249 KnownZero, KnownOne))
5250 return &CI;
5251 }
Chris Lattner2590e512006-02-07 06:56:34 +00005252
Chris Lattnerd0d51602003-06-21 23:12:02 +00005253 // If casting the result of a getelementptr instruction with no offset, turn
5254 // this into a cast of the original pointer!
5255 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005256 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005257 bool AllZeroOperands = true;
5258 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5259 if (!isa<Constant>(GEP->getOperand(i)) ||
5260 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5261 AllZeroOperands = false;
5262 break;
5263 }
5264 if (AllZeroOperands) {
5265 CI.setOperand(0, GEP->getOperand(0));
5266 return &CI;
5267 }
5268 }
5269
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005270 // If we are casting a malloc or alloca to a pointer to a type of the same
5271 // size, rewrite the allocation instruction to allocate the "right" type.
5272 //
5273 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005274 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5275 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005276
Chris Lattner86102b82005-01-01 16:22:27 +00005277 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5278 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5279 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005280 if (isa<PHINode>(Src))
5281 if (Instruction *NV = FoldOpIntoPhi(CI))
5282 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005283
5284 // If the source and destination are pointers, and this cast is equivalent to
5285 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5286 // This can enhance SROA and other transforms that want type-safe pointers.
5287 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5288 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5289 const Type *DstTy = DstPTy->getElementType();
5290 const Type *SrcTy = SrcPTy->getElementType();
5291
5292 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5293 unsigned NumZeros = 0;
5294 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005295 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5296 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005297 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5298 ++NumZeros;
5299 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005300
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005301 // If we found a path from the src to dest, create the getelementptr now.
5302 if (SrcTy == DstTy) {
5303 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5304 return new GetElementPtrInst(Src, Idxs);
5305 }
5306 }
5307
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005308 // If the source value is an instruction with only this use, we can attempt to
5309 // propagate the cast into the instruction. Also, only handle integral types
5310 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005311 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005312 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005313 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005314
5315 int NumCastsRemoved = 0;
5316 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5317 // If this cast is a truncate, evaluting in a different type always
5318 // eliminates the cast, so it is always a win. If this is a noop-cast
5319 // this just removes a noop cast which isn't pointful, but simplifies
5320 // the code. If this is a zero-extension, we need to do an AND to
5321 // maintain the clear top-part of the computation, so we require that
5322 // the input have eliminated at least one cast. If this is a sign
5323 // extension, we insert two new casts (to do the extension) so we
5324 // require that two casts have been eliminated.
5325 bool DoXForm;
5326 switch (getCastType(Src->getType(), CI.getType())) {
5327 default: assert(0 && "Unknown cast type!");
5328 case Noop:
5329 case Truncate:
5330 DoXForm = true;
5331 break;
5332 case Zeroext:
5333 DoXForm = NumCastsRemoved >= 1;
5334 break;
5335 case Signext:
5336 DoXForm = NumCastsRemoved >= 2;
5337 break;
5338 }
5339
5340 if (DoXForm) {
5341 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5342 assert(Res->getType() == CI.getType());
5343 switch (getCastType(Src->getType(), CI.getType())) {
5344 default: assert(0 && "Unknown cast type!");
5345 case Noop:
5346 case Truncate:
5347 // Just replace this cast with the result.
5348 return ReplaceInstUsesWith(CI, Res);
5349 case Zeroext: {
5350 // We need to emit an AND to clear the high bits.
5351 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5352 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5353 assert(SrcBitSize < DestBitSize && "Not a zext?");
5354 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5355 C = ConstantExpr::getCast(C, CI.getType());
5356 return BinaryOperator::createAnd(Res, C);
5357 }
5358 case Signext:
5359 // We need to emit a cast to truncate, then a cast to sext.
5360 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5361 CI.getType());
5362 }
5363 }
5364 }
5365
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005366 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005367 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5368 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005369
5370 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5371 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5372
5373 switch (SrcI->getOpcode()) {
5374 case Instruction::Add:
5375 case Instruction::Mul:
5376 case Instruction::And:
5377 case Instruction::Or:
5378 case Instruction::Xor:
5379 // If we are discarding information, or just changing the sign, rewrite.
5380 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5381 // Don't insert two casts if they cannot be eliminated. We allow two
5382 // casts to be inserted if the sizes are the same. This could only be
5383 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005384 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5385 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005386 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5387 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5388 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5389 ->getOpcode(), Op0c, Op1c);
5390 }
5391 }
Chris Lattner72086162005-05-06 02:07:39 +00005392
5393 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5394 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5395 Op1 == ConstantBool::True &&
5396 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5397 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5398 return BinaryOperator::createXor(New,
5399 ConstantInt::get(CI.getType(), 1));
5400 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005401 break;
5402 case Instruction::Shl:
5403 // Allow changing the sign of the source operand. Do not allow changing
5404 // the size of the shift, UNLESS the shift amount is a constant. We
5405 // mush not change variable sized shifts to a smaller size, because it
5406 // is undefined to shift more bits out than exist in the value.
5407 if (DestBitSize == SrcBitSize ||
5408 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5409 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5410 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5411 }
5412 break;
Chris Lattner87380412005-05-06 04:18:52 +00005413 case Instruction::Shr:
5414 // If this is a signed shr, and if all bits shifted in are about to be
5415 // truncated off, turn it into an unsigned shr to allow greater
5416 // simplifications.
5417 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5418 isa<ConstantInt>(Op1)) {
5419 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5420 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5421 // Convert to unsigned.
5422 Value *N1 = InsertOperandCastBefore(Op0,
5423 Op0->getType()->getUnsignedVersion(), &CI);
5424 // Insert the new shift, which is now unsigned.
5425 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5426 Op1, Src->getName()), CI);
5427 return new CastInst(N1, CI.getType());
5428 }
5429 }
5430 break;
5431
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005432 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005433 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005434 // We if we are just checking for a seteq of a single bit and casting it
5435 // to an integer. If so, shift the bit to the appropriate place then
5436 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005437 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005438 uint64_t Op1CV = Op1C->getZExtValue();
5439 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5440 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5441 // cast (X == 1) to int --> X iff X has only the low bit set.
5442 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5443 // cast (X != 0) to int --> X iff X has only the low bit set.
5444 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5445 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5446 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5447 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5448 // If Op1C some other power of two, convert:
5449 uint64_t KnownZero, KnownOne;
5450 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5451 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5452
5453 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5454 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5455 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5456 // (X&4) == 2 --> false
5457 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005458 Constant *Res = ConstantBool::get(isSetNE);
5459 Res = ConstantExpr::getCast(Res, CI.getType());
5460 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005461 }
5462
5463 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5464 Value *In = Op0;
5465 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005466 // Perform an unsigned shr by shiftamt. Convert input to
5467 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005468 if (In->getType()->isSigned())
5469 In = InsertNewInstBefore(new CastInst(In,
5470 In->getType()->getUnsignedVersion(), In->getName()),CI);
5471 // Insert the shift to put the result in the low bit.
5472 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005473 ConstantInt::get(Type::UByteTy, ShiftAmt),
5474 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005475 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005476
5477 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5478 Constant *One = ConstantInt::get(In->getType(), 1);
5479 In = BinaryOperator::createXor(In, One, "tmp");
5480 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005481 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005482
5483 if (CI.getType() == In->getType())
5484 return ReplaceInstUsesWith(CI, In);
5485 else
5486 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005487 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005488 }
5489 }
5490 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005491 }
5492 }
Chris Lattner99155be2006-05-25 23:24:33 +00005493
5494 if (SrcI->hasOneUse()) {
5495 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5496 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5497 // because the inputs are known to be a vector. Check to see if this is
5498 // a cast to a vector with the same # elts.
5499 if (isa<PackedType>(CI.getType()) &&
5500 cast<PackedType>(CI.getType())->getNumElements() ==
5501 SVI->getType()->getNumElements()) {
5502 CastInst *Tmp;
5503 // If either of the operands is a cast from CI.getType(), then
5504 // evaluating the shuffle in the casted destination's type will allow
5505 // us to eliminate at least one cast.
5506 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5507 Tmp->getOperand(0)->getType() == CI.getType()) ||
5508 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005509 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005510 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5511 CI.getType(), &CI);
5512 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5513 CI.getType(), &CI);
5514 // Return a new shuffle vector. Use the same element ID's, as we
5515 // know the vector types match #elts.
5516 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5517 }
5518 }
5519 }
5520 }
5521 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005522
Chris Lattner260ab202002-04-18 17:39:14 +00005523 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005524}
5525
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005526/// GetSelectFoldableOperands - We want to turn code that looks like this:
5527/// %C = or %A, %B
5528/// %D = select %cond, %C, %A
5529/// into:
5530/// %C = select %cond, %B, 0
5531/// %D = or %A, %C
5532///
5533/// Assuming that the specified instruction is an operand to the select, return
5534/// a bitmask indicating which operands of this instruction are foldable if they
5535/// equal the other incoming value of the select.
5536///
5537static unsigned GetSelectFoldableOperands(Instruction *I) {
5538 switch (I->getOpcode()) {
5539 case Instruction::Add:
5540 case Instruction::Mul:
5541 case Instruction::And:
5542 case Instruction::Or:
5543 case Instruction::Xor:
5544 return 3; // Can fold through either operand.
5545 case Instruction::Sub: // Can only fold on the amount subtracted.
5546 case Instruction::Shl: // Can only fold on the shift amount.
5547 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005548 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005549 default:
5550 return 0; // Cannot fold
5551 }
5552}
5553
5554/// GetSelectFoldableConstant - For the same transformation as the previous
5555/// function, return the identity constant that goes into the select.
5556static Constant *GetSelectFoldableConstant(Instruction *I) {
5557 switch (I->getOpcode()) {
5558 default: assert(0 && "This cannot happen!"); abort();
5559 case Instruction::Add:
5560 case Instruction::Sub:
5561 case Instruction::Or:
5562 case Instruction::Xor:
5563 return Constant::getNullValue(I->getType());
5564 case Instruction::Shl:
5565 case Instruction::Shr:
5566 return Constant::getNullValue(Type::UByteTy);
5567 case Instruction::And:
5568 return ConstantInt::getAllOnesValue(I->getType());
5569 case Instruction::Mul:
5570 return ConstantInt::get(I->getType(), 1);
5571 }
5572}
5573
Chris Lattner411336f2005-01-19 21:50:18 +00005574/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5575/// have the same opcode and only one use each. Try to simplify this.
5576Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5577 Instruction *FI) {
5578 if (TI->getNumOperands() == 1) {
5579 // If this is a non-volatile load or a cast from the same type,
5580 // merge.
5581 if (TI->getOpcode() == Instruction::Cast) {
5582 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5583 return 0;
5584 } else {
5585 return 0; // unknown unary op.
5586 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005587
Chris Lattner411336f2005-01-19 21:50:18 +00005588 // Fold this by inserting a select from the input values.
5589 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5590 FI->getOperand(0), SI.getName()+".v");
5591 InsertNewInstBefore(NewSI, SI);
5592 return new CastInst(NewSI, TI->getType());
5593 }
5594
5595 // Only handle binary operators here.
5596 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5597 return 0;
5598
5599 // Figure out if the operations have any operands in common.
5600 Value *MatchOp, *OtherOpT, *OtherOpF;
5601 bool MatchIsOpZero;
5602 if (TI->getOperand(0) == FI->getOperand(0)) {
5603 MatchOp = TI->getOperand(0);
5604 OtherOpT = TI->getOperand(1);
5605 OtherOpF = FI->getOperand(1);
5606 MatchIsOpZero = true;
5607 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5608 MatchOp = TI->getOperand(1);
5609 OtherOpT = TI->getOperand(0);
5610 OtherOpF = FI->getOperand(0);
5611 MatchIsOpZero = false;
5612 } else if (!TI->isCommutative()) {
5613 return 0;
5614 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5615 MatchOp = TI->getOperand(0);
5616 OtherOpT = TI->getOperand(1);
5617 OtherOpF = FI->getOperand(0);
5618 MatchIsOpZero = true;
5619 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5620 MatchOp = TI->getOperand(1);
5621 OtherOpT = TI->getOperand(0);
5622 OtherOpF = FI->getOperand(1);
5623 MatchIsOpZero = true;
5624 } else {
5625 return 0;
5626 }
5627
5628 // If we reach here, they do have operations in common.
5629 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5630 OtherOpF, SI.getName()+".v");
5631 InsertNewInstBefore(NewSI, SI);
5632
5633 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5634 if (MatchIsOpZero)
5635 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5636 else
5637 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5638 } else {
5639 if (MatchIsOpZero)
5640 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5641 else
5642 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5643 }
5644}
5645
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005646Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005647 Value *CondVal = SI.getCondition();
5648 Value *TrueVal = SI.getTrueValue();
5649 Value *FalseVal = SI.getFalseValue();
5650
5651 // select true, X, Y -> X
5652 // select false, X, Y -> Y
5653 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005654 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005655 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005656 else {
5657 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005658 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005659 }
Chris Lattner533bc492004-03-30 19:37:13 +00005660
5661 // select C, X, X -> X
5662 if (TrueVal == FalseVal)
5663 return ReplaceInstUsesWith(SI, TrueVal);
5664
Chris Lattner81a7a232004-10-16 18:11:37 +00005665 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5666 return ReplaceInstUsesWith(SI, FalseVal);
5667 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5668 return ReplaceInstUsesWith(SI, TrueVal);
5669 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5670 if (isa<Constant>(TrueVal))
5671 return ReplaceInstUsesWith(SI, TrueVal);
5672 else
5673 return ReplaceInstUsesWith(SI, FalseVal);
5674 }
5675
Chris Lattner1c631e82004-04-08 04:43:23 +00005676 if (SI.getType() == Type::BoolTy)
5677 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5678 if (C == ConstantBool::True) {
5679 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005680 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005681 } else {
5682 // Change: A = select B, false, C --> A = and !B, C
5683 Value *NotCond =
5684 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5685 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005686 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005687 }
5688 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5689 if (C == ConstantBool::False) {
5690 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005691 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005692 } else {
5693 // Change: A = select B, C, true --> A = or !B, C
5694 Value *NotCond =
5695 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5696 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005697 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005698 }
5699 }
5700
Chris Lattner183b3362004-04-09 19:05:30 +00005701 // Selecting between two integer constants?
5702 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5703 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5704 // select C, 1, 0 -> cast C to int
5705 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5706 return new CastInst(CondVal, SI.getType());
5707 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5708 // select C, 0, 1 -> cast !C to int
5709 Value *NotCond =
5710 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005711 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005712 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005713 }
Chris Lattner35167c32004-06-09 07:59:58 +00005714
Chris Lattner12f52fa2006-09-19 06:18:21 +00005715 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5716
5717 // (x <s 0) ? -1 : 0 -> sra x, 31
5718 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5719 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5720 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5721 bool CanXForm = false;
5722 if (CmpCst->getType()->isSigned())
5723 CanXForm = CmpCst->isNullValue() &&
5724 IC->getOpcode() == Instruction::SetLT;
5725 else {
5726 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
5727 CanXForm = (CmpCst->getRawValue() == ~0ULL >> (64-Bits+1)) &&
5728 IC->getOpcode() == Instruction::SetGT;
5729 }
5730
5731 // The comparison constant and the result are not neccessarily the
5732 // same width. In any case, the first step to do is make sure that
5733 // X is signed.
5734 Value *X = IC->getOperand(0);
5735 if (!X->getType()->isSigned())
5736 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
5737
5738 // Now that X is signed, we have to make the all ones value. Do
5739 // this by inserting a new SRA.
5740 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
5741 Constant *ShAmt = ConstantUInt::get(Type::UByteTy, Bits-1);
5742 Instruction *SRA = new ShiftInst(Instruction::Shr, X, ShAmt,"ones");
5743 InsertNewInstBefore(SRA, SI);
5744
5745 // Finally, convert to the type of the select RHS. If this is
5746 // smaller than the compare value, it will truncate the ones to fit.
5747 // If it is larger, it will sext the ones to fit.
5748 return new CastInst(SRA, SI.getType());
5749 }
5750
5751
5752 // If one of the constants is zero (we know they can't both be) and we
5753 // have a setcc instruction with zero, and we have an 'and' with the
5754 // non-constant value, eliminate this whole mess. This corresponds to
5755 // cases like this: ((X & 27) ? 27 : 0)
5756 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005757 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005758 cast<Constant>(IC->getOperand(1))->isNullValue())
5759 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5760 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005761 isa<ConstantInt>(ICA->getOperand(1)) &&
5762 (ICA->getOperand(1) == TrueValC ||
5763 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005764 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5765 // Okay, now we know that everything is set up, we just don't
5766 // know whether we have a setne or seteq and whether the true or
5767 // false val is the zero.
5768 bool ShouldNotVal = !TrueValC->isNullValue();
5769 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5770 Value *V = ICA;
5771 if (ShouldNotVal)
5772 V = InsertNewInstBefore(BinaryOperator::create(
5773 Instruction::Xor, V, ICA->getOperand(1)), SI);
5774 return ReplaceInstUsesWith(SI, V);
5775 }
Chris Lattner12f52fa2006-09-19 06:18:21 +00005776 }
Chris Lattner533bc492004-03-30 19:37:13 +00005777 }
Chris Lattner623fba12004-04-10 22:21:27 +00005778
5779 // See if we are selecting two values based on a comparison of the two values.
5780 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5781 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5782 // Transform (X == Y) ? X : Y -> Y
5783 if (SCI->getOpcode() == Instruction::SetEQ)
5784 return ReplaceInstUsesWith(SI, FalseVal);
5785 // Transform (X != Y) ? X : Y -> X
5786 if (SCI->getOpcode() == Instruction::SetNE)
5787 return ReplaceInstUsesWith(SI, TrueVal);
5788 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5789
5790 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5791 // Transform (X == Y) ? Y : X -> X
5792 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005793 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005794 // Transform (X != Y) ? Y : X -> Y
5795 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005796 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005797 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5798 }
5799 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005800
Chris Lattnera04c9042005-01-13 22:52:24 +00005801 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5802 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5803 if (TI->hasOneUse() && FI->hasOneUse()) {
5804 bool isInverse = false;
5805 Instruction *AddOp = 0, *SubOp = 0;
5806
Chris Lattner411336f2005-01-19 21:50:18 +00005807 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5808 if (TI->getOpcode() == FI->getOpcode())
5809 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5810 return IV;
5811
5812 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5813 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005814 if (TI->getOpcode() == Instruction::Sub &&
5815 FI->getOpcode() == Instruction::Add) {
5816 AddOp = FI; SubOp = TI;
5817 } else if (FI->getOpcode() == Instruction::Sub &&
5818 TI->getOpcode() == Instruction::Add) {
5819 AddOp = TI; SubOp = FI;
5820 }
5821
5822 if (AddOp) {
5823 Value *OtherAddOp = 0;
5824 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5825 OtherAddOp = AddOp->getOperand(1);
5826 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5827 OtherAddOp = AddOp->getOperand(0);
5828 }
5829
5830 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005831 // So at this point we know we have (Y -> OtherAddOp):
5832 // select C, (add X, Y), (sub X, Z)
5833 Value *NegVal; // Compute -Z
5834 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5835 NegVal = ConstantExpr::getNeg(C);
5836 } else {
5837 NegVal = InsertNewInstBefore(
5838 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005839 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005840
5841 Value *NewTrueOp = OtherAddOp;
5842 Value *NewFalseOp = NegVal;
5843 if (AddOp != TI)
5844 std::swap(NewTrueOp, NewFalseOp);
5845 Instruction *NewSel =
5846 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5847
5848 NewSel = InsertNewInstBefore(NewSel, SI);
5849 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005850 }
5851 }
5852 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005853
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005854 // See if we can fold the select into one of our operands.
5855 if (SI.getType()->isInteger()) {
5856 // See the comment above GetSelectFoldableOperands for a description of the
5857 // transformation we are doing here.
5858 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5859 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5860 !isa<Constant>(FalseVal))
5861 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5862 unsigned OpToFold = 0;
5863 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5864 OpToFold = 1;
5865 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5866 OpToFold = 2;
5867 }
5868
5869 if (OpToFold) {
5870 Constant *C = GetSelectFoldableConstant(TVI);
5871 std::string Name = TVI->getName(); TVI->setName("");
5872 Instruction *NewSel =
5873 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5874 Name);
5875 InsertNewInstBefore(NewSel, SI);
5876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5877 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5878 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5879 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5880 else {
5881 assert(0 && "Unknown instruction!!");
5882 }
5883 }
5884 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005885
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005886 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5887 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5888 !isa<Constant>(TrueVal))
5889 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5890 unsigned OpToFold = 0;
5891 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5892 OpToFold = 1;
5893 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5894 OpToFold = 2;
5895 }
5896
5897 if (OpToFold) {
5898 Constant *C = GetSelectFoldableConstant(FVI);
5899 std::string Name = FVI->getName(); FVI->setName("");
5900 Instruction *NewSel =
5901 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5902 Name);
5903 InsertNewInstBefore(NewSel, SI);
5904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5905 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5906 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5907 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5908 else {
5909 assert(0 && "Unknown instruction!!");
5910 }
5911 }
5912 }
5913 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005914
5915 if (BinaryOperator::isNot(CondVal)) {
5916 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5917 SI.setOperand(1, FalseVal);
5918 SI.setOperand(2, TrueVal);
5919 return &SI;
5920 }
5921
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005922 return 0;
5923}
5924
Chris Lattner82f2ef22006-03-06 20:18:44 +00005925/// GetKnownAlignment - If the specified pointer has an alignment that we can
5926/// determine, return it, otherwise return 0.
5927static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5928 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5929 unsigned Align = GV->getAlignment();
5930 if (Align == 0 && TD)
5931 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5932 return Align;
5933 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5934 unsigned Align = AI->getAlignment();
5935 if (Align == 0 && TD) {
5936 if (isa<AllocaInst>(AI))
5937 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5938 else if (isa<MallocInst>(AI)) {
5939 // Malloc returns maximally aligned memory.
5940 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5941 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5942 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5943 }
5944 }
5945 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005946 } else if (isa<CastInst>(V) ||
5947 (isa<ConstantExpr>(V) &&
5948 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5949 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005950 if (isa<PointerType>(CI->getOperand(0)->getType()))
5951 return GetKnownAlignment(CI->getOperand(0), TD);
5952 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005953 } else if (isa<GetElementPtrInst>(V) ||
5954 (isa<ConstantExpr>(V) &&
5955 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5956 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005957 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5958 if (BaseAlignment == 0) return 0;
5959
5960 // If all indexes are zero, it is just the alignment of the base pointer.
5961 bool AllZeroOperands = true;
5962 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5963 if (!isa<Constant>(GEPI->getOperand(i)) ||
5964 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5965 AllZeroOperands = false;
5966 break;
5967 }
5968 if (AllZeroOperands)
5969 return BaseAlignment;
5970
5971 // Otherwise, if the base alignment is >= the alignment we expect for the
5972 // base pointer type, then we know that the resultant pointer is aligned at
5973 // least as much as its type requires.
5974 if (!TD) return 0;
5975
5976 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5977 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005978 <= BaseAlignment) {
5979 const Type *GEPTy = GEPI->getType();
5980 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5981 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005982 return 0;
5983 }
5984 return 0;
5985}
5986
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005987
Chris Lattnerc66b2232006-01-13 20:11:04 +00005988/// visitCallInst - CallInst simplification. This mostly only handles folding
5989/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5990/// the heavy lifting.
5991///
Chris Lattner970c33a2003-06-19 17:00:31 +00005992Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005993 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5994 if (!II) return visitCallSite(&CI);
5995
Chris Lattner51ea1272004-02-28 05:22:00 +00005996 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5997 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005998 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005999 bool Changed = false;
6000
6001 // memmove/cpy/set of zero bytes is a noop.
6002 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6003 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6004
Chris Lattner00648e12004-10-12 04:52:52 +00006005 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6006 if (CI->getRawValue() == 1) {
6007 // Replace the instruction with just byte operations. We would
6008 // transform other cases to loads/stores, but we don't know if
6009 // alignment is sufficient.
6010 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006011 }
6012
Chris Lattner00648e12004-10-12 04:52:52 +00006013 // If we have a memmove and the source operation is a constant global,
6014 // then the source and dest pointers can't alias, so we can change this
6015 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006016 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006017 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6018 if (GVSrc->isConstant()) {
6019 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006020 const char *Name;
6021 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6022 Type::UIntTy)
6023 Name = "llvm.memcpy.i32";
6024 else
6025 Name = "llvm.memcpy.i64";
6026 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006027 CI.getCalledFunction()->getFunctionType());
6028 CI.setOperand(0, MemCpy);
6029 Changed = true;
6030 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006031 }
Chris Lattner00648e12004-10-12 04:52:52 +00006032
Chris Lattner82f2ef22006-03-06 20:18:44 +00006033 // If we can determine a pointer alignment that is bigger than currently
6034 // set, update the alignment.
6035 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6036 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6037 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6038 unsigned Align = std::min(Alignment1, Alignment2);
6039 if (MI->getAlignment()->getRawValue() < Align) {
6040 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
6041 Changed = true;
6042 }
6043 } else if (isa<MemSetInst>(MI)) {
6044 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6045 if (MI->getAlignment()->getRawValue() < Alignment) {
6046 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
6047 Changed = true;
6048 }
6049 }
6050
Chris Lattnerc66b2232006-01-13 20:11:04 +00006051 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006052 } else {
6053 switch (II->getIntrinsicID()) {
6054 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006055 case Intrinsic::ppc_altivec_lvx:
6056 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006057 case Intrinsic::x86_sse_loadu_ps:
6058 case Intrinsic::x86_sse2_loadu_pd:
6059 case Intrinsic::x86_sse2_loadu_dq:
6060 // Turn PPC lvx -> load if the pointer is known aligned.
6061 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006062 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006063 Value *Ptr = InsertCastBefore(II->getOperand(1),
6064 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006065 return new LoadInst(Ptr);
6066 }
6067 break;
6068 case Intrinsic::ppc_altivec_stvx:
6069 case Intrinsic::ppc_altivec_stvxl:
6070 // Turn stvx -> store if the pointer is known aligned.
6071 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006072 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6073 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006074 return new StoreInst(II->getOperand(1), Ptr);
6075 }
6076 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006077 case Intrinsic::x86_sse_storeu_ps:
6078 case Intrinsic::x86_sse2_storeu_pd:
6079 case Intrinsic::x86_sse2_storeu_dq:
6080 case Intrinsic::x86_sse2_storel_dq:
6081 // Turn X86 storeu -> store if the pointer is known aligned.
6082 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6083 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6084 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6085 return new StoreInst(II->getOperand(2), Ptr);
6086 }
6087 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00006088 case Intrinsic::ppc_altivec_vperm:
6089 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6090 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6091 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6092
6093 // Check that all of the elements are integer constants or undefs.
6094 bool AllEltsOk = true;
6095 for (unsigned i = 0; i != 16; ++i) {
6096 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6097 !isa<UndefValue>(Mask->getOperand(i))) {
6098 AllEltsOk = false;
6099 break;
6100 }
6101 }
6102
6103 if (AllEltsOk) {
6104 // Cast the input vectors to byte vectors.
6105 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6106 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6107 Value *Result = UndefValue::get(Op0->getType());
6108
6109 // Only extract each element once.
6110 Value *ExtractedElts[32];
6111 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6112
6113 for (unsigned i = 0; i != 16; ++i) {
6114 if (isa<UndefValue>(Mask->getOperand(i)))
6115 continue;
6116 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6117 Idx &= 31; // Match the hardware behavior.
6118
6119 if (ExtractedElts[Idx] == 0) {
6120 Instruction *Elt =
6121 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
6122 ConstantUInt::get(Type::UIntTy, Idx&15),
6123 "tmp");
6124 InsertNewInstBefore(Elt, CI);
6125 ExtractedElts[Idx] = Elt;
6126 }
6127
6128 // Insert this value into the result vector.
6129 Result = new InsertElementInst(Result, ExtractedElts[Idx],
6130 ConstantUInt::get(Type::UIntTy, i),
6131 "tmp");
6132 InsertNewInstBefore(cast<Instruction>(Result), CI);
6133 }
6134 return new CastInst(Result, CI.getType());
6135 }
6136 }
6137 break;
6138
Chris Lattner503221f2006-01-13 21:28:09 +00006139 case Intrinsic::stackrestore: {
6140 // If the save is right next to the restore, remove the restore. This can
6141 // happen when variable allocas are DCE'd.
6142 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6143 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6144 BasicBlock::iterator BI = SS;
6145 if (&*++BI == II)
6146 return EraseInstFromFunction(CI);
6147 }
6148 }
6149
6150 // If the stack restore is in a return/unwind block and if there are no
6151 // allocas or calls between the restore and the return, nuke the restore.
6152 TerminatorInst *TI = II->getParent()->getTerminator();
6153 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6154 BasicBlock::iterator BI = II;
6155 bool CannotRemove = false;
6156 for (++BI; &*BI != TI; ++BI) {
6157 if (isa<AllocaInst>(BI) ||
6158 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6159 CannotRemove = true;
6160 break;
6161 }
6162 }
6163 if (!CannotRemove)
6164 return EraseInstFromFunction(CI);
6165 }
6166 break;
6167 }
6168 }
Chris Lattner00648e12004-10-12 04:52:52 +00006169 }
6170
Chris Lattnerc66b2232006-01-13 20:11:04 +00006171 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006172}
6173
6174// InvokeInst simplification
6175//
6176Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006177 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006178}
6179
Chris Lattneraec3d942003-10-07 22:32:43 +00006180// visitCallSite - Improvements for call and invoke instructions.
6181//
6182Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006183 bool Changed = false;
6184
6185 // If the callee is a constexpr cast of a function, attempt to move the cast
6186 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006187 if (transformConstExprCastCall(CS)) return 0;
6188
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006189 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006190
Chris Lattner61d9d812005-05-13 07:09:09 +00006191 if (Function *CalleeF = dyn_cast<Function>(Callee))
6192 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6193 Instruction *OldCall = CS.getInstruction();
6194 // If the call and callee calling conventions don't match, this call must
6195 // be unreachable, as the call is undefined.
6196 new StoreInst(ConstantBool::True,
6197 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6198 if (!OldCall->use_empty())
6199 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6200 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6201 return EraseInstFromFunction(*OldCall);
6202 return 0;
6203 }
6204
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006205 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6206 // This instruction is not reachable, just remove it. We insert a store to
6207 // undef so that we know that this code is not reachable, despite the fact
6208 // that we can't modify the CFG here.
6209 new StoreInst(ConstantBool::True,
6210 UndefValue::get(PointerType::get(Type::BoolTy)),
6211 CS.getInstruction());
6212
6213 if (!CS.getInstruction()->use_empty())
6214 CS.getInstruction()->
6215 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6216
6217 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6218 // Don't break the CFG, insert a dummy cond branch.
6219 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6220 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006221 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006222 return EraseInstFromFunction(*CS.getInstruction());
6223 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006224
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006225 const PointerType *PTy = cast<PointerType>(Callee->getType());
6226 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6227 if (FTy->isVarArg()) {
6228 // See if we can optimize any arguments passed through the varargs area of
6229 // the call.
6230 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6231 E = CS.arg_end(); I != E; ++I)
6232 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6233 // If this cast does not effect the value passed through the varargs
6234 // area, we can eliminate the use of the cast.
6235 Value *Op = CI->getOperand(0);
6236 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6237 *I = Op;
6238 Changed = true;
6239 }
6240 }
6241 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006242
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006243 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006244}
6245
Chris Lattner970c33a2003-06-19 17:00:31 +00006246// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6247// attempt to move the cast to the arguments of the call/invoke.
6248//
6249bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6250 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6251 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006252 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006253 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006254 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006255 Instruction *Caller = CS.getInstruction();
6256
6257 // Okay, this is a cast from a function to a different type. Unless doing so
6258 // would cause a type conversion of one of our arguments, change this call to
6259 // be a direct call with arguments casted to the appropriate types.
6260 //
6261 const FunctionType *FT = Callee->getFunctionType();
6262 const Type *OldRetTy = Caller->getType();
6263
Chris Lattner1f7942f2004-01-14 06:06:08 +00006264 // Check to see if we are changing the return type...
6265 if (OldRetTy != FT->getReturnType()) {
6266 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006267 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6268 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006269 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006270 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006271 return false; // Cannot transform this return value...
6272
6273 // If the callsite is an invoke instruction, and the return value is used by
6274 // a PHI node in a successor, we cannot change the return type of the call
6275 // because there is no place to put the cast instruction (without breaking
6276 // the critical edge). Bail out in this case.
6277 if (!Caller->use_empty())
6278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6279 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6280 UI != E; ++UI)
6281 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6282 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006283 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006284 return false;
6285 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006286
6287 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6288 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006289
Chris Lattner970c33a2003-06-19 17:00:31 +00006290 CallSite::arg_iterator AI = CS.arg_begin();
6291 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6292 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006293 const Type *ActTy = (*AI)->getType();
6294 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6295 //Either we can cast directly, or we can upconvert the argument
6296 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6297 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6298 ParamTy->isSigned() == ActTy->isSigned() &&
6299 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6300 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6301 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006302 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006303 }
6304
6305 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6306 Callee->isExternal())
6307 return false; // Do not delete arguments unless we have a function body...
6308
6309 // Okay, we decided that this is a safe thing to do: go ahead and start
6310 // inserting cast instructions as necessary...
6311 std::vector<Value*> Args;
6312 Args.reserve(NumActualArgs);
6313
6314 AI = CS.arg_begin();
6315 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6316 const Type *ParamTy = FT->getParamType(i);
6317 if ((*AI)->getType() == ParamTy) {
6318 Args.push_back(*AI);
6319 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006320 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6321 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006322 }
6323 }
6324
6325 // If the function takes more arguments than the call was taking, add them
6326 // now...
6327 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6328 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6329
6330 // If we are removing arguments to the function, emit an obnoxious warning...
6331 if (FT->getNumParams() < NumActualArgs)
6332 if (!FT->isVarArg()) {
6333 std::cerr << "WARNING: While resolving call to function '"
6334 << Callee->getName() << "' arguments were dropped!\n";
6335 } else {
6336 // Add all of the arguments in their promoted form to the arg list...
6337 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6338 const Type *PTy = getPromotedType((*AI)->getType());
6339 if (PTy != (*AI)->getType()) {
6340 // Must promote to pass through va_arg area!
6341 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6342 InsertNewInstBefore(Cast, *Caller);
6343 Args.push_back(Cast);
6344 } else {
6345 Args.push_back(*AI);
6346 }
6347 }
6348 }
6349
6350 if (FT->getReturnType() == Type::VoidTy)
6351 Caller->setName(""); // Void type should not have a name...
6352
6353 Instruction *NC;
6354 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006355 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006356 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006357 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006358 } else {
6359 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006360 if (cast<CallInst>(Caller)->isTailCall())
6361 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006362 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006363 }
6364
6365 // Insert a cast of the return type as necessary...
6366 Value *NV = NC;
6367 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6368 if (NV->getType() != Type::VoidTy) {
6369 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006370
6371 // If this is an invoke instruction, we should insert it after the first
6372 // non-phi, instruction in the normal successor block.
6373 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6374 BasicBlock::iterator I = II->getNormalDest()->begin();
6375 while (isa<PHINode>(I)) ++I;
6376 InsertNewInstBefore(NC, *I);
6377 } else {
6378 // Otherwise, it's a call, just insert cast right after the call instr
6379 InsertNewInstBefore(NC, *Caller);
6380 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006381 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006382 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006383 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006384 }
6385 }
6386
6387 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6388 Caller->replaceAllUsesWith(NV);
6389 Caller->getParent()->getInstList().erase(Caller);
6390 removeFromWorkList(Caller);
6391 return true;
6392}
6393
6394
Chris Lattner7515cab2004-11-14 19:13:23 +00006395// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6396// operator and they all are only used by the PHI, PHI together their
6397// inputs, and do the operation once, to the result of the PHI.
6398Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6399 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6400
6401 // Scan the instruction, looking for input operations that can be folded away.
6402 // If all input operands to the phi are the same instruction (e.g. a cast from
6403 // the same type or "+42") we can pull the operation through the PHI, reducing
6404 // code size and simplifying code.
6405 Constant *ConstantOp = 0;
6406 const Type *CastSrcTy = 0;
6407 if (isa<CastInst>(FirstInst)) {
6408 CastSrcTy = FirstInst->getOperand(0)->getType();
6409 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6410 // Can fold binop or shift if the RHS is a constant.
6411 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6412 if (ConstantOp == 0) return 0;
6413 } else {
6414 return 0; // Cannot fold this operation.
6415 }
6416
6417 // Check to see if all arguments are the same operation.
6418 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6419 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6420 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6421 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6422 return 0;
6423 if (CastSrcTy) {
6424 if (I->getOperand(0)->getType() != CastSrcTy)
6425 return 0; // Cast operation must match.
6426 } else if (I->getOperand(1) != ConstantOp) {
6427 return 0;
6428 }
6429 }
6430
6431 // Okay, they are all the same operation. Create a new PHI node of the
6432 // correct type, and PHI together all of the LHS's of the instructions.
6433 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6434 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006435 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006436
6437 Value *InVal = FirstInst->getOperand(0);
6438 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006439
6440 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006441 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6442 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6443 if (NewInVal != InVal)
6444 InVal = 0;
6445 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6446 }
6447
6448 Value *PhiVal;
6449 if (InVal) {
6450 // The new PHI unions all of the same values together. This is really
6451 // common, so we handle it intelligently here for compile-time speed.
6452 PhiVal = InVal;
6453 delete NewPN;
6454 } else {
6455 InsertNewInstBefore(NewPN, PN);
6456 PhiVal = NewPN;
6457 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006458
Chris Lattner7515cab2004-11-14 19:13:23 +00006459 // Insert and return the new operation.
6460 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006461 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006462 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006463 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006464 else
6465 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006466 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006467}
Chris Lattner48a44f72002-05-02 17:06:02 +00006468
Chris Lattner71536432005-01-17 05:10:15 +00006469/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6470/// that is dead.
6471static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6472 if (PN->use_empty()) return true;
6473 if (!PN->hasOneUse()) return false;
6474
6475 // Remember this node, and if we find the cycle, return.
6476 if (!PotentiallyDeadPHIs.insert(PN).second)
6477 return true;
6478
6479 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6480 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006481
Chris Lattner71536432005-01-17 05:10:15 +00006482 return false;
6483}
6484
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006485// PHINode simplification
6486//
Chris Lattner113f4f42002-06-25 16:13:24 +00006487Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006488 // If LCSSA is around, don't mess with Phi nodes
6489 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006490
Owen Andersonae8aa642006-07-10 22:03:18 +00006491 if (Value *V = PN.hasConstantValue())
6492 return ReplaceInstUsesWith(PN, V);
6493
6494 // If the only user of this instruction is a cast instruction, and all of the
6495 // incoming values are constants, change this PHI to merge together the casted
6496 // constants.
6497 if (PN.hasOneUse())
6498 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6499 if (CI->getType() != PN.getType()) { // noop casts will be folded
6500 bool AllConstant = true;
6501 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6502 if (!isa<Constant>(PN.getIncomingValue(i))) {
6503 AllConstant = false;
6504 break;
6505 }
6506 if (AllConstant) {
6507 // Make a new PHI with all casted values.
6508 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6509 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6510 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6511 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6512 PN.getIncomingBlock(i));
6513 }
6514
6515 // Update the cast instruction.
6516 CI->setOperand(0, New);
6517 WorkList.push_back(CI); // revisit the cast instruction to fold.
6518 WorkList.push_back(New); // Make sure to revisit the new Phi
6519 return &PN; // PN is now dead!
6520 }
6521 }
6522
6523 // If all PHI operands are the same operation, pull them through the PHI,
6524 // reducing code size.
6525 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6526 PN.getIncomingValue(0)->hasOneUse())
6527 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6528 return Result;
6529
6530 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6531 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6532 // PHI)... break the cycle.
6533 if (PN.hasOneUse())
6534 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6535 std::set<PHINode*> PotentiallyDeadPHIs;
6536 PotentiallyDeadPHIs.insert(&PN);
6537 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6538 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6539 }
6540
Chris Lattner91daeb52003-12-19 05:58:40 +00006541 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006542}
6543
Chris Lattner69193f92004-04-05 01:30:19 +00006544static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6545 Instruction *InsertPoint,
6546 InstCombiner *IC) {
6547 unsigned PS = IC->getTargetData().getPointerSize();
6548 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006549 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6550 // We must insert a cast to ensure we sign-extend.
6551 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6552 V->getName()), *InsertPoint);
6553 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6554 *InsertPoint);
6555}
6556
Chris Lattner48a44f72002-05-02 17:06:02 +00006557
Chris Lattner113f4f42002-06-25 16:13:24 +00006558Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006559 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006560 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006561 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006562 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006563 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006564
Chris Lattner81a7a232004-10-16 18:11:37 +00006565 if (isa<UndefValue>(GEP.getOperand(0)))
6566 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6567
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006568 bool HasZeroPointerIndex = false;
6569 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6570 HasZeroPointerIndex = C->isNullValue();
6571
6572 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006573 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006574
Chris Lattner69193f92004-04-05 01:30:19 +00006575 // Eliminate unneeded casts for indices.
6576 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006577 gep_type_iterator GTI = gep_type_begin(GEP);
6578 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6579 if (isa<SequentialType>(*GTI)) {
6580 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6581 Value *Src = CI->getOperand(0);
6582 const Type *SrcTy = Src->getType();
6583 const Type *DestTy = CI->getType();
6584 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006585 if (SrcTy->getPrimitiveSizeInBits() ==
6586 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006587 // We can always eliminate a cast from ulong or long to the other.
6588 // We can always eliminate a cast from uint to int or the other on
6589 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006590 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006591 MadeChange = true;
6592 GEP.setOperand(i, Src);
6593 }
6594 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6595 SrcTy->getPrimitiveSize() == 4) {
6596 // We can always eliminate a cast from int to [u]long. We can
6597 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6598 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006599 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006600 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006601 MadeChange = true;
6602 GEP.setOperand(i, Src);
6603 }
Chris Lattner69193f92004-04-05 01:30:19 +00006604 }
6605 }
6606 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006607 // If we are using a wider index than needed for this platform, shrink it
6608 // to what we need. If the incoming value needs a cast instruction,
6609 // insert it. This explicit cast can make subsequent optimizations more
6610 // obvious.
6611 Value *Op = GEP.getOperand(i);
6612 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006613 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006614 GEP.setOperand(i, ConstantExpr::getCast(C,
6615 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006616 MadeChange = true;
6617 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006618 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6619 Op->getName()), GEP);
6620 GEP.setOperand(i, Op);
6621 MadeChange = true;
6622 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006623
6624 // If this is a constant idx, make sure to canonicalize it to be a signed
6625 // operand, otherwise CSE and other optimizations are pessimized.
6626 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6627 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6628 CUI->getType()->getSignedVersion()));
6629 MadeChange = true;
6630 }
Chris Lattner69193f92004-04-05 01:30:19 +00006631 }
6632 if (MadeChange) return &GEP;
6633
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006634 // Combine Indices - If the source pointer to this getelementptr instruction
6635 // is a getelementptr instruction, combine the indices of the two
6636 // getelementptr instructions into a single instruction.
6637 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006638 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006639 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006640 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006641
6642 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006643 // Note that if our source is a gep chain itself that we wait for that
6644 // chain to be resolved before we perform this transformation. This
6645 // avoids us creating a TON of code in some cases.
6646 //
6647 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6648 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6649 return 0; // Wait until our source is folded to completion.
6650
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006651 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006652
6653 // Find out whether the last index in the source GEP is a sequential idx.
6654 bool EndsWithSequential = false;
6655 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6656 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006657 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006658
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006659 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006660 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006661 // Replace: gep (gep %P, long B), long A, ...
6662 // With: T = long A+B; gep %P, T, ...
6663 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006664 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006665 if (SO1 == Constant::getNullValue(SO1->getType())) {
6666 Sum = GO1;
6667 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6668 Sum = SO1;
6669 } else {
6670 // If they aren't the same type, convert both to an integer of the
6671 // target's pointer size.
6672 if (SO1->getType() != GO1->getType()) {
6673 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6674 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6675 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6676 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6677 } else {
6678 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006679 if (SO1->getType()->getPrimitiveSize() == PS) {
6680 // Convert GO1 to SO1's type.
6681 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6682
6683 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6684 // Convert SO1 to GO1's type.
6685 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6686 } else {
6687 const Type *PT = TD->getIntPtrType();
6688 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6689 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6690 }
6691 }
6692 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006693 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6694 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6695 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006696 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6697 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006698 }
Chris Lattner69193f92004-04-05 01:30:19 +00006699 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006700
6701 // Recycle the GEP we already have if possible.
6702 if (SrcGEPOperands.size() == 2) {
6703 GEP.setOperand(0, SrcGEPOperands[0]);
6704 GEP.setOperand(1, Sum);
6705 return &GEP;
6706 } else {
6707 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6708 SrcGEPOperands.end()-1);
6709 Indices.push_back(Sum);
6710 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6711 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006712 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006713 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006714 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006715 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006716 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6717 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006718 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6719 }
6720
6721 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006722 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006723
Chris Lattner5f667a62004-05-07 22:09:22 +00006724 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006725 // GEP of global variable. If all of the indices for this GEP are
6726 // constants, we can promote this to a constexpr instead of an instruction.
6727
6728 // Scan for nonconstants...
6729 std::vector<Constant*> Indices;
6730 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6731 for (; I != E && isa<Constant>(*I); ++I)
6732 Indices.push_back(cast<Constant>(*I));
6733
6734 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006735 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006736
6737 // Replace all uses of the GEP with the new constexpr...
6738 return ReplaceInstUsesWith(GEP, CE);
6739 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006740 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6741 if (!isa<PointerType>(X->getType())) {
6742 // Not interesting. Source pointer must be a cast from pointer.
6743 } else if (HasZeroPointerIndex) {
6744 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6745 // into : GEP [10 x ubyte]* X, long 0, ...
6746 //
6747 // This occurs when the program declares an array extern like "int X[];"
6748 //
6749 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6750 const PointerType *XTy = cast<PointerType>(X->getType());
6751 if (const ArrayType *XATy =
6752 dyn_cast<ArrayType>(XTy->getElementType()))
6753 if (const ArrayType *CATy =
6754 dyn_cast<ArrayType>(CPTy->getElementType()))
6755 if (CATy->getElementType() == XATy->getElementType()) {
6756 // At this point, we know that the cast source type is a pointer
6757 // to an array of the same type as the destination pointer
6758 // array. Because the array type is never stepped over (there
6759 // is a leading zero) we can fold the cast into this GEP.
6760 GEP.setOperand(0, X);
6761 return &GEP;
6762 }
6763 } else if (GEP.getNumOperands() == 2) {
6764 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006765 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6766 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006767 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6768 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6769 if (isa<ArrayType>(SrcElTy) &&
6770 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6771 TD->getTypeSize(ResElTy)) {
6772 Value *V = InsertNewInstBefore(
6773 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6774 GEP.getOperand(1), GEP.getName()), GEP);
6775 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006776 }
Chris Lattner2a893292005-09-13 18:36:04 +00006777
6778 // Transform things like:
6779 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6780 // (where tmp = 8*tmp2) into:
6781 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6782
6783 if (isa<ArrayType>(SrcElTy) &&
6784 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6785 uint64_t ArrayEltSize =
6786 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6787
6788 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6789 // allow either a mul, shift, or constant here.
6790 Value *NewIdx = 0;
6791 ConstantInt *Scale = 0;
6792 if (ArrayEltSize == 1) {
6793 NewIdx = GEP.getOperand(1);
6794 Scale = ConstantInt::get(NewIdx->getType(), 1);
6795 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006796 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006797 Scale = CI;
6798 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6799 if (Inst->getOpcode() == Instruction::Shl &&
6800 isa<ConstantInt>(Inst->getOperand(1))) {
6801 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6802 if (Inst->getType()->isSigned())
6803 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6804 else
6805 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6806 NewIdx = Inst->getOperand(0);
6807 } else if (Inst->getOpcode() == Instruction::Mul &&
6808 isa<ConstantInt>(Inst->getOperand(1))) {
6809 Scale = cast<ConstantInt>(Inst->getOperand(1));
6810 NewIdx = Inst->getOperand(0);
6811 }
6812 }
6813
6814 // If the index will be to exactly the right offset with the scale taken
6815 // out, perform the transformation.
6816 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6817 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6818 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006819 (int64_t)C->getRawValue() /
6820 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006821 else
6822 Scale = ConstantUInt::get(Scale->getType(),
6823 Scale->getRawValue() / ArrayEltSize);
6824 if (Scale->getRawValue() != 1) {
6825 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6826 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6827 NewIdx = InsertNewInstBefore(Sc, GEP);
6828 }
6829
6830 // Insert the new GEP instruction.
6831 Instruction *Idx =
6832 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6833 NewIdx, GEP.getName());
6834 Idx = InsertNewInstBefore(Idx, GEP);
6835 return new CastInst(Idx, GEP.getType());
6836 }
6837 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006838 }
Chris Lattnerca081252001-12-14 16:52:21 +00006839 }
6840
Chris Lattnerca081252001-12-14 16:52:21 +00006841 return 0;
6842}
6843
Chris Lattner1085bdf2002-11-04 16:18:53 +00006844Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6845 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6846 if (AI.isArrayAllocation()) // Check C != 1
6847 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6848 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006849 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006850
6851 // Create and insert the replacement instruction...
6852 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006853 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006854 else {
6855 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006856 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006857 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006858
6859 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006860
Chris Lattner1085bdf2002-11-04 16:18:53 +00006861 // Scan to the end of the allocation instructions, to skip over a block of
6862 // allocas if possible...
6863 //
6864 BasicBlock::iterator It = New;
6865 while (isa<AllocationInst>(*It)) ++It;
6866
6867 // Now that I is pointing to the first non-allocation-inst in the block,
6868 // insert our getelementptr instruction...
6869 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006870 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6871 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6872 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006873
6874 // Now make everything use the getelementptr instead of the original
6875 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006876 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006877 } else if (isa<UndefValue>(AI.getArraySize())) {
6878 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006879 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006880
6881 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6882 // Note that we only do this for alloca's, because malloc should allocate and
6883 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006884 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006885 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006886 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6887
Chris Lattner1085bdf2002-11-04 16:18:53 +00006888 return 0;
6889}
6890
Chris Lattner8427bff2003-12-07 01:24:23 +00006891Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6892 Value *Op = FI.getOperand(0);
6893
6894 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6895 if (CastInst *CI = dyn_cast<CastInst>(Op))
6896 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6897 FI.setOperand(0, CI->getOperand(0));
6898 return &FI;
6899 }
6900
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006901 // free undef -> unreachable.
6902 if (isa<UndefValue>(Op)) {
6903 // Insert a new store to null because we cannot modify the CFG here.
6904 new StoreInst(ConstantBool::True,
6905 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6906 return EraseInstFromFunction(FI);
6907 }
6908
Chris Lattnerf3a36602004-02-28 04:57:37 +00006909 // If we have 'free null' delete the instruction. This can happen in stl code
6910 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006911 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006912 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006913
Chris Lattner8427bff2003-12-07 01:24:23 +00006914 return 0;
6915}
6916
6917
Chris Lattner72684fe2005-01-31 05:51:45 +00006918/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006919static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6920 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006921 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006922
6923 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006924 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006925 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006926
Chris Lattnerebca4762006-04-02 05:37:12 +00006927 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6928 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006929 // If the source is an array, the code below will not succeed. Check to
6930 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6931 // constants.
6932 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6933 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6934 if (ASrcTy->getNumElements() != 0) {
6935 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6936 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6937 SrcTy = cast<PointerType>(CastOp->getType());
6938 SrcPTy = SrcTy->getElementType();
6939 }
6940
Chris Lattnerebca4762006-04-02 05:37:12 +00006941 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6942 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006943 // Do not allow turning this into a load of an integer, which is then
6944 // casted to a pointer, this pessimizes pointer analysis a lot.
6945 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006946 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006947 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006948
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006949 // Okay, we are casting from one integer or pointer type to another of
6950 // the same size. Instead of casting the pointer before the load, cast
6951 // the result of the loaded value.
6952 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6953 CI->getName(),
6954 LI.isVolatile()),LI);
6955 // Now cast the result of the load.
6956 return new CastInst(NewLoad, LI.getType());
6957 }
Chris Lattner35e24772004-07-13 01:49:43 +00006958 }
6959 }
6960 return 0;
6961}
6962
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006963/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006964/// from this value cannot trap. If it is not obviously safe to load from the
6965/// specified pointer, we do a quick local scan of the basic block containing
6966/// ScanFrom, to determine if the address is already accessed.
6967static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6968 // If it is an alloca or global variable, it is always safe to load from.
6969 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6970
6971 // Otherwise, be a little bit agressive by scanning the local block where we
6972 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006973 // from/to. If so, the previous load or store would have already trapped,
6974 // so there is no harm doing an extra load (also, CSE will later eliminate
6975 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006976 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6977
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006978 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006979 --BBI;
6980
6981 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6982 if (LI->getOperand(0) == V) return true;
6983 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6984 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006985
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006986 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006987 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006988}
6989
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006990Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6991 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006992
Chris Lattnera9d84e32005-05-01 04:24:53 +00006993 // load (cast X) --> cast (load X) iff safe
6994 if (CastInst *CI = dyn_cast<CastInst>(Op))
6995 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6996 return Res;
6997
6998 // None of the following transforms are legal for volatile loads.
6999 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007000
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007001 if (&LI.getParent()->front() != &LI) {
7002 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007003 // If the instruction immediately before this is a store to the same
7004 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007005 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7006 if (SI->getOperand(1) == LI.getOperand(0))
7007 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007008 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7009 if (LIB->getOperand(0) == LI.getOperand(0))
7010 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007011 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007012
7013 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7014 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7015 isa<UndefValue>(GEPI->getOperand(0))) {
7016 // Insert a new store to null instruction before the load to indicate
7017 // that this code is not reachable. We do this instead of inserting
7018 // an unreachable instruction directly because we cannot modify the
7019 // CFG.
7020 new StoreInst(UndefValue::get(LI.getType()),
7021 Constant::getNullValue(Op->getType()), &LI);
7022 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7023 }
7024
Chris Lattner81a7a232004-10-16 18:11:37 +00007025 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007026 // load null/undef -> undef
7027 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007028 // Insert a new store to null instruction before the load to indicate that
7029 // this code is not reachable. We do this instead of inserting an
7030 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007031 new StoreInst(UndefValue::get(LI.getType()),
7032 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007033 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007034 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007035
Chris Lattner81a7a232004-10-16 18:11:37 +00007036 // Instcombine load (constant global) into the value loaded.
7037 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7038 if (GV->isConstant() && !GV->isExternal())
7039 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007040
Chris Lattner81a7a232004-10-16 18:11:37 +00007041 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7042 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7043 if (CE->getOpcode() == Instruction::GetElementPtr) {
7044 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7045 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007046 if (Constant *V =
7047 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007048 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007049 if (CE->getOperand(0)->isNullValue()) {
7050 // Insert a new store to null instruction before the load to indicate
7051 // that this code is not reachable. We do this instead of inserting
7052 // an unreachable instruction directly because we cannot modify the
7053 // CFG.
7054 new StoreInst(UndefValue::get(LI.getType()),
7055 Constant::getNullValue(Op->getType()), &LI);
7056 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7057 }
7058
Chris Lattner81a7a232004-10-16 18:11:37 +00007059 } else if (CE->getOpcode() == Instruction::Cast) {
7060 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7061 return Res;
7062 }
7063 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007064
Chris Lattnera9d84e32005-05-01 04:24:53 +00007065 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007066 // Change select and PHI nodes to select values instead of addresses: this
7067 // helps alias analysis out a lot, allows many others simplifications, and
7068 // exposes redundancy in the code.
7069 //
7070 // Note that we cannot do the transformation unless we know that the
7071 // introduced loads cannot trap! Something like this is valid as long as
7072 // the condition is always false: load (select bool %C, int* null, int* %G),
7073 // but it would not be valid if we transformed it to load from null
7074 // unconditionally.
7075 //
7076 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7077 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007078 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7079 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007080 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007081 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007082 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007083 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007084 return new SelectInst(SI->getCondition(), V1, V2);
7085 }
7086
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007087 // load (select (cond, null, P)) -> load P
7088 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7089 if (C->isNullValue()) {
7090 LI.setOperand(0, SI->getOperand(2));
7091 return &LI;
7092 }
7093
7094 // load (select (cond, P, null)) -> load P
7095 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7096 if (C->isNullValue()) {
7097 LI.setOperand(0, SI->getOperand(1));
7098 return &LI;
7099 }
7100
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007101 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7102 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007103 bool Safe = PN->getParent() == LI.getParent();
7104
7105 // Scan all of the instructions between the PHI and the load to make
7106 // sure there are no instructions that might possibly alter the value
7107 // loaded from the PHI.
7108 if (Safe) {
7109 BasicBlock::iterator I = &LI;
7110 for (--I; !isa<PHINode>(I); --I)
7111 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7112 Safe = false;
7113 break;
7114 }
7115 }
7116
7117 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007118 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007119 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007120 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007121
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007122 if (Safe) {
7123 // Create the PHI.
7124 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7125 InsertNewInstBefore(NewPN, *PN);
7126 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7127
7128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7129 BasicBlock *BB = PN->getIncomingBlock(i);
7130 Value *&TheLoad = LoadMap[BB];
7131 if (TheLoad == 0) {
7132 Value *InVal = PN->getIncomingValue(i);
7133 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7134 InVal->getName()+".val"),
7135 *BB->getTerminator());
7136 }
7137 NewPN->addIncoming(TheLoad, BB);
7138 }
7139 return ReplaceInstUsesWith(LI, NewPN);
7140 }
7141 }
7142 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007143 return 0;
7144}
7145
Chris Lattner72684fe2005-01-31 05:51:45 +00007146/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7147/// when possible.
7148static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7149 User *CI = cast<User>(SI.getOperand(1));
7150 Value *CastOp = CI->getOperand(0);
7151
7152 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7153 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7154 const Type *SrcPTy = SrcTy->getElementType();
7155
7156 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7157 // If the source is an array, the code below will not succeed. Check to
7158 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7159 // constants.
7160 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7161 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7162 if (ASrcTy->getNumElements() != 0) {
7163 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7164 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7165 SrcTy = cast<PointerType>(CastOp->getType());
7166 SrcPTy = SrcTy->getElementType();
7167 }
7168
7169 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007170 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007171 IC.getTargetData().getTypeSize(DestPTy)) {
7172
7173 // Okay, we are casting from one integer or pointer type to another of
7174 // the same size. Instead of casting the pointer before the store, cast
7175 // the value to be stored.
7176 Value *NewCast;
7177 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7178 NewCast = ConstantExpr::getCast(C, SrcPTy);
7179 else
7180 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7181 SrcPTy,
7182 SI.getOperand(0)->getName()+".c"), SI);
7183
7184 return new StoreInst(NewCast, CastOp);
7185 }
7186 }
7187 }
7188 return 0;
7189}
7190
Chris Lattner31f486c2005-01-31 05:36:43 +00007191Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7192 Value *Val = SI.getOperand(0);
7193 Value *Ptr = SI.getOperand(1);
7194
7195 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007196 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007197 ++NumCombined;
7198 return 0;
7199 }
7200
Chris Lattner5997cf92006-02-08 03:25:32 +00007201 // Do really simple DSE, to catch cases where there are several consequtive
7202 // stores to the same location, separated by a few arithmetic operations. This
7203 // situation often occurs with bitfield accesses.
7204 BasicBlock::iterator BBI = &SI;
7205 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7206 --ScanInsts) {
7207 --BBI;
7208
7209 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7210 // Prev store isn't volatile, and stores to the same location?
7211 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7212 ++NumDeadStore;
7213 ++BBI;
7214 EraseInstFromFunction(*PrevSI);
7215 continue;
7216 }
7217 break;
7218 }
7219
Chris Lattnerdab43b22006-05-26 19:19:20 +00007220 // If this is a load, we have to stop. However, if the loaded value is from
7221 // the pointer we're loading and is producing the pointer we're storing,
7222 // then *this* store is dead (X = load P; store X -> P).
7223 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7224 if (LI == Val && LI->getOperand(0) == Ptr) {
7225 EraseInstFromFunction(SI);
7226 ++NumCombined;
7227 return 0;
7228 }
7229 // Otherwise, this is a load from some other location. Stores before it
7230 // may not be dead.
7231 break;
7232 }
7233
Chris Lattner5997cf92006-02-08 03:25:32 +00007234 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007235 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007236 break;
7237 }
7238
7239
7240 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007241
7242 // store X, null -> turns into 'unreachable' in SimplifyCFG
7243 if (isa<ConstantPointerNull>(Ptr)) {
7244 if (!isa<UndefValue>(Val)) {
7245 SI.setOperand(0, UndefValue::get(Val->getType()));
7246 if (Instruction *U = dyn_cast<Instruction>(Val))
7247 WorkList.push_back(U); // Dropped a use.
7248 ++NumCombined;
7249 }
7250 return 0; // Do not modify these!
7251 }
7252
7253 // store undef, Ptr -> noop
7254 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007255 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007256 ++NumCombined;
7257 return 0;
7258 }
7259
Chris Lattner72684fe2005-01-31 05:51:45 +00007260 // If the pointer destination is a cast, see if we can fold the cast into the
7261 // source instead.
7262 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7263 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7264 return Res;
7265 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7266 if (CE->getOpcode() == Instruction::Cast)
7267 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7268 return Res;
7269
Chris Lattner219175c2005-09-12 23:23:25 +00007270
7271 // If this store is the last instruction in the basic block, and if the block
7272 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007273 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007274 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7275 if (BI->isUnconditional()) {
7276 // Check to see if the successor block has exactly two incoming edges. If
7277 // so, see if the other predecessor contains a store to the same location.
7278 // if so, insert a PHI node (if needed) and move the stores down.
7279 BasicBlock *Dest = BI->getSuccessor(0);
7280
7281 pred_iterator PI = pred_begin(Dest);
7282 BasicBlock *Other = 0;
7283 if (*PI != BI->getParent())
7284 Other = *PI;
7285 ++PI;
7286 if (PI != pred_end(Dest)) {
7287 if (*PI != BI->getParent())
7288 if (Other)
7289 Other = 0;
7290 else
7291 Other = *PI;
7292 if (++PI != pred_end(Dest))
7293 Other = 0;
7294 }
7295 if (Other) { // If only one other pred...
7296 BBI = Other->getTerminator();
7297 // Make sure this other block ends in an unconditional branch and that
7298 // there is an instruction before the branch.
7299 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7300 BBI != Other->begin()) {
7301 --BBI;
7302 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7303
7304 // If this instruction is a store to the same location.
7305 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7306 // Okay, we know we can perform this transformation. Insert a PHI
7307 // node now if we need it.
7308 Value *MergedVal = OtherStore->getOperand(0);
7309 if (MergedVal != SI.getOperand(0)) {
7310 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7311 PN->reserveOperandSpace(2);
7312 PN->addIncoming(SI.getOperand(0), SI.getParent());
7313 PN->addIncoming(OtherStore->getOperand(0), Other);
7314 MergedVal = InsertNewInstBefore(PN, Dest->front());
7315 }
7316
7317 // Advance to a place where it is safe to insert the new store and
7318 // insert it.
7319 BBI = Dest->begin();
7320 while (isa<PHINode>(BBI)) ++BBI;
7321 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7322 OtherStore->isVolatile()), *BBI);
7323
7324 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007325 EraseInstFromFunction(SI);
7326 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007327 ++NumCombined;
7328 return 0;
7329 }
7330 }
7331 }
7332 }
7333
Chris Lattner31f486c2005-01-31 05:36:43 +00007334 return 0;
7335}
7336
7337
Chris Lattner9eef8a72003-06-04 04:46:00 +00007338Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7339 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007340 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007341 BasicBlock *TrueDest;
7342 BasicBlock *FalseDest;
7343 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7344 !isa<Constant>(X)) {
7345 // Swap Destinations and condition...
7346 BI.setCondition(X);
7347 BI.setSuccessor(0, FalseDest);
7348 BI.setSuccessor(1, TrueDest);
7349 return &BI;
7350 }
7351
7352 // Cannonicalize setne -> seteq
7353 Instruction::BinaryOps Op; Value *Y;
7354 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7355 TrueDest, FalseDest)))
7356 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7357 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7358 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7359 std::string Name = I->getName(); I->setName("");
7360 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7361 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007362 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007363 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007364 BI.setSuccessor(0, FalseDest);
7365 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007366 removeFromWorkList(I);
7367 I->getParent()->getInstList().erase(I);
7368 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007369 return &BI;
7370 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007371
Chris Lattner9eef8a72003-06-04 04:46:00 +00007372 return 0;
7373}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007374
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007375Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7376 Value *Cond = SI.getCondition();
7377 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7378 if (I->getOpcode() == Instruction::Add)
7379 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7380 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7381 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007382 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007383 AddRHS));
7384 SI.setOperand(0, I->getOperand(0));
7385 WorkList.push_back(I);
7386 return &SI;
7387 }
7388 }
7389 return 0;
7390}
7391
Chris Lattner6bc98652006-03-05 00:22:33 +00007392/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7393/// is to leave as a vector operation.
7394static bool CheapToScalarize(Value *V, bool isConstant) {
7395 if (isa<ConstantAggregateZero>(V))
7396 return true;
7397 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7398 if (isConstant) return true;
7399 // If all elts are the same, we can extract.
7400 Constant *Op0 = C->getOperand(0);
7401 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7402 if (C->getOperand(i) != Op0)
7403 return false;
7404 return true;
7405 }
7406 Instruction *I = dyn_cast<Instruction>(V);
7407 if (!I) return false;
7408
7409 // Insert element gets simplified to the inserted element or is deleted if
7410 // this is constant idx extract element and its a constant idx insertelt.
7411 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7412 isa<ConstantInt>(I->getOperand(2)))
7413 return true;
7414 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7415 return true;
7416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7417 if (BO->hasOneUse() &&
7418 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7419 CheapToScalarize(BO->getOperand(1), isConstant)))
7420 return true;
7421
7422 return false;
7423}
7424
Chris Lattner12249be2006-05-25 23:48:38 +00007425/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7426/// elements into values that are larger than the #elts in the input.
7427static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7428 unsigned NElts = SVI->getType()->getNumElements();
7429 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7430 return std::vector<unsigned>(NElts, 0);
7431 if (isa<UndefValue>(SVI->getOperand(2)))
7432 return std::vector<unsigned>(NElts, 2*NElts);
7433
7434 std::vector<unsigned> Result;
7435 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7436 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7437 if (isa<UndefValue>(CP->getOperand(i)))
7438 Result.push_back(NElts*2); // undef -> 8
7439 else
7440 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7441 return Result;
7442}
7443
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007444/// FindScalarElement - Given a vector and an element number, see if the scalar
7445/// value is already around as a register, for example if it were inserted then
7446/// extracted from the vector.
7447static Value *FindScalarElement(Value *V, unsigned EltNo) {
7448 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7449 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007450 unsigned Width = PTy->getNumElements();
7451 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007452 return UndefValue::get(PTy->getElementType());
7453
7454 if (isa<UndefValue>(V))
7455 return UndefValue::get(PTy->getElementType());
7456 else if (isa<ConstantAggregateZero>(V))
7457 return Constant::getNullValue(PTy->getElementType());
7458 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7459 return CP->getOperand(EltNo);
7460 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7461 // If this is an insert to a variable element, we don't know what it is.
7462 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7463 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7464
7465 // If this is an insert to the element we are looking for, return the
7466 // inserted value.
7467 if (EltNo == IIElt) return III->getOperand(1);
7468
7469 // Otherwise, the insertelement doesn't modify the value, recurse on its
7470 // vector input.
7471 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007472 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007473 unsigned InEl = getShuffleMask(SVI)[EltNo];
7474 if (InEl < Width)
7475 return FindScalarElement(SVI->getOperand(0), InEl);
7476 else if (InEl < Width*2)
7477 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7478 else
7479 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007480 }
7481
7482 // Otherwise, we don't know.
7483 return 0;
7484}
7485
Robert Bocchinoa8352962006-01-13 22:48:06 +00007486Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007487
Chris Lattner92346c32006-03-31 18:25:14 +00007488 // If packed val is undef, replace extract with scalar undef.
7489 if (isa<UndefValue>(EI.getOperand(0)))
7490 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7491
7492 // If packed val is constant 0, replace extract with scalar 0.
7493 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7494 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7495
Robert Bocchinoa8352962006-01-13 22:48:06 +00007496 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7497 // If packed val is constant with uniform operands, replace EI
7498 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007499 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007500 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007501 if (C->getOperand(i) != op0) {
7502 op0 = 0;
7503 break;
7504 }
7505 if (op0)
7506 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007507 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007508
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007509 // If extracting a specified index from the vector, see if we can recursively
7510 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007511 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007512 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7513 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007514 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007515
Chris Lattner83f65782006-05-25 22:53:38 +00007516 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007517 if (I->hasOneUse()) {
7518 // Push extractelement into predecessor operation if legal and
7519 // profitable to do so
7520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007521 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7522 if (CheapToScalarize(BO, isConstantElt)) {
7523 ExtractElementInst *newEI0 =
7524 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7525 EI.getName()+".lhs");
7526 ExtractElementInst *newEI1 =
7527 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7528 EI.getName()+".rhs");
7529 InsertNewInstBefore(newEI0, EI);
7530 InsertNewInstBefore(newEI1, EI);
7531 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7532 }
7533 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007534 Value *Ptr = InsertCastBefore(I->getOperand(0),
7535 PointerType::get(EI.getType()), EI);
7536 GetElementPtrInst *GEP =
7537 new GetElementPtrInst(Ptr, EI.getOperand(1),
7538 I->getName() + ".gep");
7539 InsertNewInstBefore(GEP, EI);
7540 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007541 }
7542 }
7543 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7544 // Extracting the inserted element?
7545 if (IE->getOperand(2) == EI.getOperand(1))
7546 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7547 // If the inserted and extracted elements are constants, they must not
7548 // be the same value, extract from the pre-inserted value instead.
7549 if (isa<Constant>(IE->getOperand(2)) &&
7550 isa<Constant>(EI.getOperand(1))) {
7551 AddUsesToWorkList(EI);
7552 EI.setOperand(0, IE->getOperand(0));
7553 return &EI;
7554 }
7555 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7556 // If this is extracting an element from a shufflevector, figure out where
7557 // it came from and extract from the appropriate input element instead.
7558 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007559 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7560 Value *Src;
7561 if (SrcIdx < SVI->getType()->getNumElements())
7562 Src = SVI->getOperand(0);
7563 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7564 SrcIdx -= SVI->getType()->getNumElements();
7565 Src = SVI->getOperand(1);
7566 } else {
7567 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007568 }
Chris Lattner12249be2006-05-25 23:48:38 +00007569 return new ExtractElementInst(Src,
7570 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007571 }
7572 }
Chris Lattner83f65782006-05-25 22:53:38 +00007573 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007574 return 0;
7575}
7576
Chris Lattner90951862006-04-16 00:51:47 +00007577/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7578/// elements from either LHS or RHS, return the shuffle mask and true.
7579/// Otherwise, return false.
7580static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7581 std::vector<Constant*> &Mask) {
7582 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7583 "Invalid CollectSingleShuffleElements");
7584 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7585
7586 if (isa<UndefValue>(V)) {
7587 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7588 return true;
7589 } else if (V == LHS) {
7590 for (unsigned i = 0; i != NumElts; ++i)
7591 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7592 return true;
7593 } else if (V == RHS) {
7594 for (unsigned i = 0; i != NumElts; ++i)
7595 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7596 return true;
7597 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7598 // If this is an insert of an extract from some other vector, include it.
7599 Value *VecOp = IEI->getOperand(0);
7600 Value *ScalarOp = IEI->getOperand(1);
7601 Value *IdxOp = IEI->getOperand(2);
7602
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007603 if (!isa<ConstantInt>(IdxOp))
7604 return false;
7605 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7606
7607 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7608 // Okay, we can handle this if the vector we are insertinting into is
7609 // transitively ok.
7610 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7611 // If so, update the mask to reflect the inserted undef.
7612 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7613 return true;
7614 }
7615 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7616 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007617 EI->getOperand(0)->getType() == V->getType()) {
7618 unsigned ExtractedIdx =
7619 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007620
7621 // This must be extracting from either LHS or RHS.
7622 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7623 // Okay, we can handle this if the vector we are insertinting into is
7624 // transitively ok.
7625 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7626 // If so, update the mask to reflect the inserted value.
7627 if (EI->getOperand(0) == LHS) {
7628 Mask[InsertedIdx & (NumElts-1)] =
7629 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7630 } else {
7631 assert(EI->getOperand(0) == RHS);
7632 Mask[InsertedIdx & (NumElts-1)] =
7633 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7634
7635 }
7636 return true;
7637 }
7638 }
7639 }
7640 }
7641 }
7642 // TODO: Handle shufflevector here!
7643
7644 return false;
7645}
7646
7647/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7648/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7649/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007650static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007651 Value *&RHS) {
7652 assert(isa<PackedType>(V->getType()) &&
7653 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007654 "Invalid shuffle!");
7655 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7656
7657 if (isa<UndefValue>(V)) {
7658 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7659 return V;
7660 } else if (isa<ConstantAggregateZero>(V)) {
7661 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7662 return V;
7663 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7664 // If this is an insert of an extract from some other vector, include it.
7665 Value *VecOp = IEI->getOperand(0);
7666 Value *ScalarOp = IEI->getOperand(1);
7667 Value *IdxOp = IEI->getOperand(2);
7668
7669 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7670 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7671 EI->getOperand(0)->getType() == V->getType()) {
7672 unsigned ExtractedIdx =
7673 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7674 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7675
7676 // Either the extracted from or inserted into vector must be RHSVec,
7677 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007678 if (EI->getOperand(0) == RHS || RHS == 0) {
7679 RHS = EI->getOperand(0);
7680 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007681 Mask[InsertedIdx & (NumElts-1)] =
7682 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7683 return V;
7684 }
7685
Chris Lattner90951862006-04-16 00:51:47 +00007686 if (VecOp == RHS) {
7687 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007688 // Everything but the extracted element is replaced with the RHS.
7689 for (unsigned i = 0; i != NumElts; ++i) {
7690 if (i != InsertedIdx)
7691 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7692 }
7693 return V;
7694 }
Chris Lattner90951862006-04-16 00:51:47 +00007695
7696 // If this insertelement is a chain that comes from exactly these two
7697 // vectors, return the vector and the effective shuffle.
7698 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7699 return EI->getOperand(0);
7700
Chris Lattner39fac442006-04-15 01:39:45 +00007701 }
7702 }
7703 }
Chris Lattner90951862006-04-16 00:51:47 +00007704 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007705
7706 // Otherwise, can't do anything fancy. Return an identity vector.
7707 for (unsigned i = 0; i != NumElts; ++i)
7708 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7709 return V;
7710}
7711
7712Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7713 Value *VecOp = IE.getOperand(0);
7714 Value *ScalarOp = IE.getOperand(1);
7715 Value *IdxOp = IE.getOperand(2);
7716
7717 // If the inserted element was extracted from some other vector, and if the
7718 // indexes are constant, try to turn this into a shufflevector operation.
7719 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7720 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7721 EI->getOperand(0)->getType() == IE.getType()) {
7722 unsigned NumVectorElts = IE.getType()->getNumElements();
7723 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7724 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7725
7726 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7727 return ReplaceInstUsesWith(IE, VecOp);
7728
7729 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7730 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7731
7732 // If we are extracting a value from a vector, then inserting it right
7733 // back into the same place, just use the input vector.
7734 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7735 return ReplaceInstUsesWith(IE, VecOp);
7736
7737 // We could theoretically do this for ANY input. However, doing so could
7738 // turn chains of insertelement instructions into a chain of shufflevector
7739 // instructions, and right now we do not merge shufflevectors. As such,
7740 // only do this in a situation where it is clear that there is benefit.
7741 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7742 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7743 // the values of VecOp, except then one read from EIOp0.
7744 // Build a new shuffle mask.
7745 std::vector<Constant*> Mask;
7746 if (isa<UndefValue>(VecOp))
7747 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7748 else {
7749 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7750 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7751 NumVectorElts));
7752 }
7753 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7754 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7755 ConstantPacked::get(Mask));
7756 }
7757
7758 // If this insertelement isn't used by some other insertelement, turn it
7759 // (and any insertelements it points to), into one big shuffle.
7760 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7761 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007762 Value *RHS = 0;
7763 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7764 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7765 // We now have a shuffle of LHS, RHS, Mask.
7766 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007767 }
7768 }
7769 }
7770
7771 return 0;
7772}
7773
7774
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007775Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7776 Value *LHS = SVI.getOperand(0);
7777 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007778 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007779
7780 bool MadeChange = false;
7781
Chris Lattner12249be2006-05-25 23:48:38 +00007782 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007783 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7784
Chris Lattner39fac442006-04-15 01:39:45 +00007785 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7786 // the undef, change them to undefs.
7787
Chris Lattner12249be2006-05-25 23:48:38 +00007788 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7789 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7790 if (LHS == RHS || isa<UndefValue>(LHS)) {
7791 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007792 // shuffle(undef,undef,mask) -> undef.
7793 return ReplaceInstUsesWith(SVI, LHS);
7794 }
7795
Chris Lattner12249be2006-05-25 23:48:38 +00007796 // Remap any references to RHS to use LHS.
7797 std::vector<Constant*> Elts;
7798 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007799 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007800 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007801 else {
7802 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7803 (Mask[i] < e && isa<UndefValue>(LHS)))
7804 Mask[i] = 2*e; // Turn into undef.
7805 else
7806 Mask[i] &= (e-1); // Force to LHS.
7807 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7808 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007809 }
Chris Lattner12249be2006-05-25 23:48:38 +00007810 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007811 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007812 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007813 LHS = SVI.getOperand(0);
7814 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007815 MadeChange = true;
7816 }
7817
Chris Lattner0e477162006-05-26 00:29:06 +00007818 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007819 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007820
Chris Lattner12249be2006-05-25 23:48:38 +00007821 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7822 if (Mask[i] >= e*2) continue; // Ignore undef values.
7823 // Is this an identity shuffle of the LHS value?
7824 isLHSID &= (Mask[i] == i);
7825
7826 // Is this an identity shuffle of the RHS value?
7827 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007828 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007829
Chris Lattner12249be2006-05-25 23:48:38 +00007830 // Eliminate identity shuffles.
7831 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7832 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007833
Chris Lattner0e477162006-05-26 00:29:06 +00007834 // If the LHS is a shufflevector itself, see if we can combine it with this
7835 // one without producing an unusual shuffle. Here we are really conservative:
7836 // we are absolutely afraid of producing a shuffle mask not in the input
7837 // program, because the code gen may not be smart enough to turn a merged
7838 // shuffle into two specific shuffles: it may produce worse code. As such,
7839 // we only merge two shuffles if the result is one of the two input shuffle
7840 // masks. In this case, merging the shuffles just removes one instruction,
7841 // which we know is safe. This is good for things like turning:
7842 // (splat(splat)) -> splat.
7843 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7844 if (isa<UndefValue>(RHS)) {
7845 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7846
7847 std::vector<unsigned> NewMask;
7848 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7849 if (Mask[i] >= 2*e)
7850 NewMask.push_back(2*e);
7851 else
7852 NewMask.push_back(LHSMask[Mask[i]]);
7853
7854 // If the result mask is equal to the src shuffle or this shuffle mask, do
7855 // the replacement.
7856 if (NewMask == LHSMask || NewMask == Mask) {
7857 std::vector<Constant*> Elts;
7858 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7859 if (NewMask[i] >= e*2) {
7860 Elts.push_back(UndefValue::get(Type::UIntTy));
7861 } else {
7862 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7863 }
7864 }
7865 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7866 LHSSVI->getOperand(1),
7867 ConstantPacked::get(Elts));
7868 }
7869 }
7870 }
7871
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007872 return MadeChange ? &SVI : 0;
7873}
7874
7875
Robert Bocchinoa8352962006-01-13 22:48:06 +00007876
Chris Lattner99f48c62002-09-02 04:59:56 +00007877void InstCombiner::removeFromWorkList(Instruction *I) {
7878 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7879 WorkList.end());
7880}
7881
Chris Lattner39c98bb2004-12-08 23:43:58 +00007882
7883/// TryToSinkInstruction - Try to move the specified instruction from its
7884/// current block into the beginning of DestBlock, which can only happen if it's
7885/// safe to move the instruction past all of the instructions between it and the
7886/// end of its block.
7887static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7888 assert(I->hasOneUse() && "Invariants didn't hold!");
7889
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007890 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7891 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007892
Chris Lattner39c98bb2004-12-08 23:43:58 +00007893 // Do not sink alloca instructions out of the entry block.
7894 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7895 return false;
7896
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007897 // We can only sink load instructions if there is nothing between the load and
7898 // the end of block that could change the value.
7899 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007900 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7901 Scan != E; ++Scan)
7902 if (Scan->mayWriteToMemory())
7903 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007904 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007905
7906 BasicBlock::iterator InsertPos = DestBlock->begin();
7907 while (isa<PHINode>(InsertPos)) ++InsertPos;
7908
Chris Lattner9f269e42005-08-08 19:11:57 +00007909 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007910 ++NumSunkInst;
7911 return true;
7912}
7913
Chris Lattner1443bc52006-05-11 17:11:52 +00007914/// OptimizeConstantExpr - Given a constant expression and target data layout
7915/// information, symbolically evaluation the constant expr to something simpler
7916/// if possible.
7917static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7918 if (!TD) return CE;
7919
7920 Constant *Ptr = CE->getOperand(0);
7921 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7922 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7923 // If this is a constant expr gep that is effectively computing an
7924 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7925 bool isFoldableGEP = true;
7926 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7927 if (!isa<ConstantInt>(CE->getOperand(i)))
7928 isFoldableGEP = false;
7929 if (isFoldableGEP) {
7930 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7931 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7932 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7933 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7934 return ConstantExpr::getCast(C, CE->getType());
7935 }
7936 }
7937
7938 return CE;
7939}
7940
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007941
7942/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7943/// all reachable code to the worklist.
7944///
7945/// This has a couple of tricks to make the code faster and more powerful. In
7946/// particular, we constant fold and DCE instructions as we go, to avoid adding
7947/// them to the worklist (this significantly speeds up instcombine on code where
7948/// many instructions are dead or constant). Additionally, if we find a branch
7949/// whose condition is a known constant, we only visit the reachable successors.
7950///
7951static void AddReachableCodeToWorklist(BasicBlock *BB,
7952 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007953 std::vector<Instruction*> &WorkList,
7954 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007955 // We have now visited this block! If we've already been here, bail out.
7956 if (!Visited.insert(BB).second) return;
7957
7958 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7959 Instruction *Inst = BBI++;
7960
7961 // DCE instruction if trivially dead.
7962 if (isInstructionTriviallyDead(Inst)) {
7963 ++NumDeadInst;
7964 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7965 Inst->eraseFromParent();
7966 continue;
7967 }
7968
7969 // ConstantProp instruction if trivially constant.
7970 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007971 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7972 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007973 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7974 Inst->replaceAllUsesWith(C);
7975 ++NumConstProp;
7976 Inst->eraseFromParent();
7977 continue;
7978 }
7979
7980 WorkList.push_back(Inst);
7981 }
7982
7983 // Recursively visit successors. If this is a branch or switch on a constant,
7984 // only visit the reachable successor.
7985 TerminatorInst *TI = BB->getTerminator();
7986 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7987 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7988 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007989 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7990 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007991 return;
7992 }
7993 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7994 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7995 // See if this is an explicit destination.
7996 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7997 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007998 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007999 return;
8000 }
8001
8002 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008003 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008004 return;
8005 }
8006 }
8007
8008 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008009 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008010}
8011
Chris Lattner113f4f42002-06-25 16:13:24 +00008012bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008013 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008014 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008015
Chris Lattner4ed40f72005-07-07 20:40:38 +00008016 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008017 // Do a depth-first traversal of the function, populate the worklist with
8018 // the reachable instructions. Ignore blocks that are not reachable. Keep
8019 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008020 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008021 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008022
Chris Lattner4ed40f72005-07-07 20:40:38 +00008023 // Do a quick scan over the function. If we find any blocks that are
8024 // unreachable, remove any instructions inside of them. This prevents
8025 // the instcombine code from having to deal with some bad special cases.
8026 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8027 if (!Visited.count(BB)) {
8028 Instruction *Term = BB->getTerminator();
8029 while (Term != BB->begin()) { // Remove instrs bottom-up
8030 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008031
Chris Lattner4ed40f72005-07-07 20:40:38 +00008032 DEBUG(std::cerr << "IC: DCE: " << *I);
8033 ++NumDeadInst;
8034
8035 if (!I->use_empty())
8036 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8037 I->eraseFromParent();
8038 }
8039 }
8040 }
Chris Lattnerca081252001-12-14 16:52:21 +00008041
8042 while (!WorkList.empty()) {
8043 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8044 WorkList.pop_back();
8045
Chris Lattner1443bc52006-05-11 17:11:52 +00008046 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008047 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008048 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008049 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008050 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008051 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008052
Chris Lattnercd517ff2005-01-28 19:32:01 +00008053 DEBUG(std::cerr << "IC: DCE: " << *I);
8054
8055 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008056 removeFromWorkList(I);
8057 continue;
8058 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008059
Chris Lattner1443bc52006-05-11 17:11:52 +00008060 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008061 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008062 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8063 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008064 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8065
Chris Lattner1443bc52006-05-11 17:11:52 +00008066 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008067 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008068 ReplaceInstUsesWith(*I, C);
8069
Chris Lattner99f48c62002-09-02 04:59:56 +00008070 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008071 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008072 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008073 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008074 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008075
Chris Lattner39c98bb2004-12-08 23:43:58 +00008076 // See if we can trivially sink this instruction to a successor basic block.
8077 if (I->hasOneUse()) {
8078 BasicBlock *BB = I->getParent();
8079 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8080 if (UserParent != BB) {
8081 bool UserIsSuccessor = false;
8082 // See if the user is one of our successors.
8083 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8084 if (*SI == UserParent) {
8085 UserIsSuccessor = true;
8086 break;
8087 }
8088
8089 // If the user is one of our immediate successors, and if that successor
8090 // only has us as a predecessors (we'd have to split the critical edge
8091 // otherwise), we can keep going.
8092 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8093 next(pred_begin(UserParent)) == pred_end(UserParent))
8094 // Okay, the CFG is simple enough, try to sink this instruction.
8095 Changed |= TryToSinkInstruction(I, UserParent);
8096 }
8097 }
8098
Chris Lattnerca081252001-12-14 16:52:21 +00008099 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008100 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008101 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008102 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008103 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008104 DEBUG(std::cerr << "IC: Old = " << *I
8105 << " New = " << *Result);
8106
Chris Lattner396dbfe2004-06-09 05:08:07 +00008107 // Everything uses the new instruction now.
8108 I->replaceAllUsesWith(Result);
8109
8110 // Push the new instruction and any users onto the worklist.
8111 WorkList.push_back(Result);
8112 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008113
8114 // Move the name to the new instruction first...
8115 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008116 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008117
8118 // Insert the new instruction into the basic block...
8119 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008120 BasicBlock::iterator InsertPos = I;
8121
8122 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8123 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8124 ++InsertPos;
8125
8126 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008127
Chris Lattner63d75af2004-05-01 23:27:23 +00008128 // Make sure that we reprocess all operands now that we reduced their
8129 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008130 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8131 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8132 WorkList.push_back(OpI);
8133
Chris Lattner396dbfe2004-06-09 05:08:07 +00008134 // Instructions can end up on the worklist more than once. Make sure
8135 // we do not process an instruction that has been deleted.
8136 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008137
8138 // Erase the old instruction.
8139 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008140 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008141 DEBUG(std::cerr << "IC: MOD = " << *I);
8142
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008143 // If the instruction was modified, it's possible that it is now dead.
8144 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008145 if (isInstructionTriviallyDead(I)) {
8146 // Make sure we process all operands now that we are reducing their
8147 // use counts.
8148 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8149 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8150 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008151
Chris Lattner63d75af2004-05-01 23:27:23 +00008152 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008153 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008154 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008155 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008156 } else {
8157 WorkList.push_back(Result);
8158 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008159 }
Chris Lattner053c0932002-05-14 15:24:07 +00008160 }
Chris Lattner260ab202002-04-18 17:39:14 +00008161 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008162 }
8163 }
8164
Chris Lattner260ab202002-04-18 17:39:14 +00008165 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008166}
8167
Brian Gaeke38b79e82004-07-27 17:43:21 +00008168FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008169 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008170}
Brian Gaeke960707c2003-11-11 22:41:34 +00008171