blob: 6961806bcb79b05d8ff37c0c5bb5869dbb7e7c1d [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-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 Lattnerdf17af12003-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 Lattner2cd91962003-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 Lattnere92d2f42003-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 Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-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 Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattnerdd841ae2002-04-18 17:39:14 +000059namespace {
Chris Lattnera92f6962002-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 Lattner9ca96412006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000065
Chris Lattnerf4b54612006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000072
Chris Lattner7bcc0e72004-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 Lattner6dce1a72006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner7bcc0e72004-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 Lattner62b14df2002-09-02 04:59:56 +000092 // removeFromWorkList - remove all instances of I from the worklist.
93 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000094 public:
Chris Lattner7e708292002-06-25 16:13:24 +000095 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000096
Chris Lattner97e52e42002-04-28 21:27:06 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000098 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +000099 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000100 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000101 }
102
Chris Lattner28977af2004-04-05 01:30:19 +0000103 TargetData &getTargetData() const { return *TD; }
104
Chris Lattnerdd841ae2002-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 Lattner233f7dc2002-08-12 21:17:25 +0000109 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000110 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000111 //
Chris Lattner7e708292002-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 Lattner484d3cf2005-04-24 06:59:08 +0000120 Instruction *visitSetCondInst(SetCondInst &I);
121 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
122
Chris Lattner574da9b2005-01-13 20:14:25 +0000123 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
124 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000125 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner4d5542c2006-01-06 07:12:35 +0000126 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
127 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000129 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
130 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000131 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 Instruction *visitCallInst(CallInst &CI);
133 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000134 Instruction *visitPHINode(PHINode &PN);
135 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000136 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000137 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000138 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000139 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000140 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000141 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000142 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000143 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000144 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000145
146 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000147 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000148
Chris Lattner9fe38862003-06-19 17:00:31 +0000149 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000150 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000151 bool transformConstExprCastCall(CallSite CS);
152
Chris Lattner28977af2004-04-05 01:30:19 +0000153 public:
Chris Lattner8b170942002-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 Lattner955f3312004-09-28 21:48:02 +0000157 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000158 assert(New && New->getParent() == 0 &&
159 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-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 Lattner4cb170c2004-02-23 06:38:22 +0000163 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000164 }
165
Chris Lattner0c967662004-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 Brukmanfd939082005-04-21 23:48:37 +0000171
Chris Lattnere2ed0572006-04-06 19:19:17 +0000172 if (Constant *CV = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CV, Ty);
174
Chris Lattner0c967662004-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 Lattner8b170942002-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 Lattner7bcc0e72004-02-28 05:22:00 +0000187 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-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 Lattner17be6352004-10-18 02:59:09 +0000194 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000195 return &I;
196 }
Chris Lattner8b170942002-08-09 23:47:40 +0000197 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000198
Chris Lattner6dce1a72006-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 Lattnerf8c36f52006-02-12 08:02:11 +0000211 if (Instruction *I = dyn_cast<Instruction>(New))
212 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000213 return true;
214 }
215
Chris Lattner7bcc0e72004-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 Lattner954f66a2004-11-18 21:41:39 +0000224 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000225 return 0; // Don't do anything with FI
226 }
227
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000228 private:
Chris Lattner24c8e382003-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 Lattnerc8802d22003-03-11 00:12:48 +0000236 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000237 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000238 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000239
Chris Lattner255d8912006-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 Lattner4e998b22004-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 Lattnerbac32862004-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 Lattnerbd7b5ff2003-09-19 17:17:26 +0000254 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
255 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000256
257 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
258 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000259 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
260 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000261 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000262 Instruction *MatchBSwap(BinaryOperator &I);
263
Chris Lattner70074e02006-05-13 02:06:03 +0000264 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000265 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000266
Chris Lattner7f8897f2006-08-27 22:42:52 +0000267 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000268}
269
Chris Lattner4f98c562003-03-10 21:43:22 +0000270// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000271// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000272static unsigned getComplexity(Value *V) {
273 if (isa<Instruction>(V)) {
274 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000275 return 3;
276 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000277 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000278 if (isa<Argument>(V)) return 3;
279 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000280}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000281
Chris Lattnerc8802d22003-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 Lattnerfd059242003-10-15 16:48:29 +0000285 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000286}
287
Chris Lattner4cb170c2004-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 Lattner5dd04022004-06-17 18:16:02 +0000291 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-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 Lattnereed48272005-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 Lattner33a61132006-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 Lattner01575b72006-05-25 23:24:33 +0000420 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-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 Lattner4f98c562003-03-10 21:43:22 +0000443// SimplifyCommutative - This performs a few simplifications for commutative
444// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000445//
Chris Lattner4f98c562003-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 Lattnerc8802d22003-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 Lattner4f98c562003-03-10 21:43:22 +0000452//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000453bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000454 bool Changed = false;
455 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
456 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000457
Chris Lattner4f98c562003-03-10 21:43:22 +0000458 if (!I.isAssociative()) return Changed;
459 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-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 Lattner2a9c8472003-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 Lattnerc8802d22003-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 Lattner2a9c8472003-05-27 16:40:51 +0000476 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-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 Brukmanfd939082005-04-21 23:48:37 +0000484 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000485 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000486 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000487}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000488
Chris Lattner8d969642003-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 Lattnerb35dde12002-05-06 16:49:18 +0000491//
Chris Lattner8d969642003-03-10 23:06:50 +0000492static inline Value *dyn_castNegVal(Value *V) {
493 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000494 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000495
Chris Lattner0ce85802004-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 Lattner8d969642003-03-10 23:06:50 +0000499 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000500}
501
Chris Lattner8d969642003-03-10 23:06:50 +0000502static inline Value *dyn_castNotVal(Value *V) {
503 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000504 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000505
506 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000507 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000508 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000509 return 0;
510}
511
Chris Lattnerc8802d22003-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 Lattner50af16a2004-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 Lattnerc8802d22003-03-11 00:12:48 +0000516//
Chris Lattner50af16a2004-11-13 19:50:12 +0000517static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000518 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000519 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000523 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000524 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-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 Lattnerc8802d22003-03-11 00:12:48 +0000531 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000532}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000533
Chris Lattner574da9b2005-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 Lattner955f3312004-09-28 21:48:02 +0000544// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000545static ConstantInt *AddOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getAdd(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000548}
Chris Lattnera96879a2004-09-29 17:40:11 +0000549static ConstantInt *SubOne(ConstantInt *C) {
550 return cast<ConstantInt>(ConstantExpr::getSub(C,
551 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000552}
553
Chris Lattner255d8912006-02-11 09:31:47 +0000554/// GetConstantInType - Return a ConstantInt with the specified type and value.
555///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000556static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner255d8912006-02-11 09:31:47 +0000557 if (Ty->isUnsigned())
558 return ConstantUInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000559 else if (Ty->getTypeID() == Type::BoolTyID)
560 return ConstantBool::get(Val);
Chris Lattner255d8912006-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 Lattner68d5ff22006-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 Lattner5931c542005-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 Lattner3bedbd92006-02-07 07:27:52 +0000576 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-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 Lattner68d5ff22006-02-09 07:38:58 +0000580 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
581 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000582 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000583 KnownZero = ~KnownOne & Mask;
584 return;
585 }
586
587 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000588 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000589 return; // Limit search depth.
590
591 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000592 Instruction *I = dyn_cast<Instruction>(V);
593 if (!I) return;
594
Chris Lattnere3158302006-05-04 17:33:35 +0000595 Mask &= V->getType()->getIntegralTypeMask();
596
Chris Lattner255d8912006-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 Lattner68d5ff22006-02-09 07:38:58 +0000654 return;
655 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000656
Chris Lattner255d8912006-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 Lattner60de63d2005-10-09 06:36:35 +0000661
Chris Lattner255d8912006-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 Lattner74c51a02006-02-07 08:05:22 +0000674
Chris Lattner255d8912006-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 Lattner68d5ff22006-02-09 07:38:58 +0000679 KnownZero |= NewBits;
Chris Lattner255d8912006-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 Lattner68d5ff22006-02-09 07:38:58 +0000717 } else {
Chris Lattner255d8912006-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 Lattner68d5ff22006-02-09 07:38:58 +0000732 }
733 }
734 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000735 }
Chris Lattner255d8912006-02-11 09:31:47 +0000736 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000737 }
Chris Lattner74c51a02006-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 Lattner68d5ff22006-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 Lattner5931c542005-09-24 23:43:33 +0000748}
749
Chris Lattner255d8912006-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 Lattnerbf5d8a82006-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 Lattner255d8912006-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 Lattner6dce1a72006-02-07 06:56:34 +0000825 unsigned Depth) {
Chris Lattner255d8912006-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 Lattner6dce1a72006-02-07 06:56:34 +0000834 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-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 Lattner6dce1a72006-02-07 06:56:34 +0000838 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000839 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000840 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-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 Lattner74c51a02006-02-07 08:05:22 +0000844 if (V != UndefValue::get(V->getType()))
845 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
846 return false;
Chris Lattner6dce1a72006-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 Lattnere3158302006-05-04 17:33:35 +0000854 DemandedMask &= V->getType()->getIntegralTypeMask();
855
Chris Lattner255d8912006-02-11 09:31:47 +0000856 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000857 switch (I->getOpcode()) {
858 default: break;
859 case Instruction::And:
Chris Lattner255d8912006-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 Lattnerf8c36f52006-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 Lattner255d8912006-02-11 09:31:47 +0000884 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000885 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-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 Cohenbce48052006-02-18 03:20:33 +0000905 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000906 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000907 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000908 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-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 Begeman368e18d2006-02-16 21:11:51 +0000915 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
916 (DemandedMask & (~KnownZero2)))
917 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-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 Lattnerf8c36f52006-02-12 08:02:11 +0000952 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-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 Lattner6dce1a72006-02-07 06:56:34 +0000960 }
961 }
Chris Lattner255d8912006-02-11 09:31:47 +0000962
Chris Lattnerf8c36f52006-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 Lattner255d8912006-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 Lattner6dce1a72006-02-07 06:56:34 +00001007 case Instruction::Cast: {
1008 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001009 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001010
Chris Lattner255d8912006-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()) {
1014 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1015 KnownZero, KnownOne, Depth+1))
1016 return true;
1017 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1018 break;
1019 }
1020
1021 // Sign or Zero extension. Compute the bits in the result that are not
1022 // present in the input.
1023 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1024 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1025
1026 // Handle zero extension.
1027 if (!SrcTy->isSigned()) {
1028 DemandedMask &= SrcTy->getIntegralTypeMask();
1029 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1030 KnownZero, KnownOne, Depth+1))
1031 return true;
1032 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1033 // The top bits are known to be zero.
1034 KnownZero |= NewBits;
1035 } else {
1036 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +00001037 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1038 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1039
1040 // If any of the sign extended bits are demanded, we know that the sign
1041 // bit is demanded.
1042 if (NewBits & DemandedMask)
1043 InputDemandedBits |= InSignBit;
1044
1045 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +00001046 KnownZero, KnownOne, Depth+1))
1047 return true;
1048 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049
1050 // If the sign bit of the input is known set or clear, then we know the
1051 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001052
Chris Lattner255d8912006-02-11 09:31:47 +00001053 // If the input sign bit is known zero, or if the NewBits are not demanded
1054 // convert this into a zero extension.
1055 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +00001056 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001057 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001058 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +00001059 I->getOperand(0)->getName());
1060 InsertNewInstBefore(NewVal, *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001061 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001062 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1063 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001064 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +00001065 } else if (KnownOne & InSignBit) { // Input sign bit known set
1066 KnownOne |= NewBits;
1067 KnownZero &= ~NewBits;
1068 } else { // Input sign bit unknown
1069 KnownZero &= ~NewBits;
1070 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001071 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001072 }
Chris Lattner255d8912006-02-11 09:31:47 +00001073 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001074 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001075 case Instruction::Shl:
Chris Lattner255d8912006-02-11 09:31:47 +00001076 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1077 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1078 KnownZero, KnownOne, Depth+1))
1079 return true;
1080 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1081 KnownZero <<= SA->getValue();
1082 KnownOne <<= SA->getValue();
1083 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1084 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001085 break;
1086 case Instruction::Shr:
Chris Lattner255d8912006-02-11 09:31:47 +00001087 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1088 unsigned ShAmt = SA->getValue();
1089
1090 // Compute the new bits that are at the top now.
1091 uint64_t HighBits = (1ULL << ShAmt)-1;
1092 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001093 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001094 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001095 if (SimplifyDemandedBits(I->getOperand(0),
1096 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001097 KnownZero, KnownOne, Depth+1))
1098 return true;
1099 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001100 KnownZero &= TypeMask;
1101 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +00001102 KnownZero >>= ShAmt;
1103 KnownOne >>= ShAmt;
1104 KnownZero |= HighBits; // high bits known zero.
1105 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001106 if (SimplifyDemandedBits(I->getOperand(0),
1107 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001108 KnownZero, KnownOne, Depth+1))
1109 return true;
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001111 KnownZero &= TypeMask;
1112 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +00001113 KnownZero >>= SA->getValue();
1114 KnownOne >>= SA->getValue();
1115
1116 // Handle the sign bits.
1117 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1118 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1119
1120 // If the input sign bit is known to be zero, or if none of the top bits
1121 // are demanded, turn this into an unsigned shift right.
1122 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1123 // Convert the input to unsigned.
1124 Instruction *NewVal;
1125 NewVal = new CastInst(I->getOperand(0),
1126 I->getType()->getUnsignedVersion(),
1127 I->getOperand(0)->getName());
1128 InsertNewInstBefore(NewVal, *I);
1129 // Perform the unsigned shift right.
1130 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1131 InsertNewInstBefore(NewVal, *I);
1132 // Then cast that to the destination type.
1133 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1134 InsertNewInstBefore(NewVal, *I);
1135 return UpdateValueUsesWith(I, NewVal);
1136 } else if (KnownOne & SignBit) { // New bits are known one.
1137 KnownOne |= HighBits;
1138 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001139 }
Chris Lattner255d8912006-02-11 09:31:47 +00001140 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001141 break;
1142 }
Chris Lattner255d8912006-02-11 09:31:47 +00001143
1144 // If the client is only demanding bits that we know, return the known
1145 // constant.
1146 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1147 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001148 return false;
1149}
1150
Chris Lattner955f3312004-09-28 21:48:02 +00001151// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1152// true when both operands are equal...
1153//
1154static bool isTrueWhenEqual(Instruction &I) {
1155 return I.getOpcode() == Instruction::SetEQ ||
1156 I.getOpcode() == Instruction::SetGE ||
1157 I.getOpcode() == Instruction::SetLE;
1158}
Chris Lattner564a7272003-08-13 19:01:45 +00001159
1160/// AssociativeOpt - Perform an optimization on an associative operator. This
1161/// function is designed to check a chain of associative operators for a
1162/// potential to apply a certain optimization. Since the optimization may be
1163/// applicable if the expression was reassociated, this checks the chain, then
1164/// reassociates the expression as necessary to expose the optimization
1165/// opportunity. This makes use of a special Functor, which must define
1166/// 'shouldApply' and 'apply' methods.
1167///
1168template<typename Functor>
1169Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1170 unsigned Opcode = Root.getOpcode();
1171 Value *LHS = Root.getOperand(0);
1172
1173 // Quick check, see if the immediate LHS matches...
1174 if (F.shouldApply(LHS))
1175 return F.apply(Root);
1176
1177 // Otherwise, if the LHS is not of the same opcode as the root, return.
1178 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001179 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001180 // Should we apply this transform to the RHS?
1181 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1182
1183 // If not to the RHS, check to see if we should apply to the LHS...
1184 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1185 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1186 ShouldApply = true;
1187 }
1188
1189 // If the functor wants to apply the optimization to the RHS of LHSI,
1190 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1191 if (ShouldApply) {
1192 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001193
Chris Lattner564a7272003-08-13 19:01:45 +00001194 // Now all of the instructions are in the current basic block, go ahead
1195 // and perform the reassociation.
1196 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1197
1198 // First move the selected RHS to the LHS of the root...
1199 Root.setOperand(0, LHSI->getOperand(1));
1200
1201 // Make what used to be the LHS of the root be the user of the root...
1202 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001203 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001204 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1205 return 0;
1206 }
Chris Lattner65725312004-04-16 18:08:07 +00001207 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001208 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001209 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1210 BasicBlock::iterator ARI = &Root; ++ARI;
1211 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1212 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001213
1214 // Now propagate the ExtraOperand down the chain of instructions until we
1215 // get to LHSI.
1216 while (TmpLHSI != LHSI) {
1217 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001218 // Move the instruction to immediately before the chain we are
1219 // constructing to avoid breaking dominance properties.
1220 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1221 BB->getInstList().insert(ARI, NextLHSI);
1222 ARI = NextLHSI;
1223
Chris Lattner564a7272003-08-13 19:01:45 +00001224 Value *NextOp = NextLHSI->getOperand(1);
1225 NextLHSI->setOperand(1, ExtraOperand);
1226 TmpLHSI = NextLHSI;
1227 ExtraOperand = NextOp;
1228 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001229
Chris Lattner564a7272003-08-13 19:01:45 +00001230 // Now that the instructions are reassociated, have the functor perform
1231 // the transformation...
1232 return F.apply(Root);
1233 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001234
Chris Lattner564a7272003-08-13 19:01:45 +00001235 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1236 }
1237 return 0;
1238}
1239
1240
1241// AddRHS - Implements: X + X --> X << 1
1242struct AddRHS {
1243 Value *RHS;
1244 AddRHS(Value *rhs) : RHS(rhs) {}
1245 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1246 Instruction *apply(BinaryOperator &Add) const {
1247 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1248 ConstantInt::get(Type::UByteTy, 1));
1249 }
1250};
1251
1252// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1253// iff C1&C2 == 0
1254struct AddMaskingAnd {
1255 Constant *C2;
1256 AddMaskingAnd(Constant *c) : C2(c) {}
1257 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001258 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001259 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001260 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001261 }
1262 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001263 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001264 }
1265};
1266
Chris Lattner6e7ba452005-01-01 16:22:27 +00001267static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001268 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001269 if (isa<CastInst>(I)) {
1270 if (Constant *SOC = dyn_cast<Constant>(SO))
1271 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001272
Chris Lattner6e7ba452005-01-01 16:22:27 +00001273 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1274 SO->getName() + ".cast"), I);
1275 }
1276
Chris Lattner2eefe512004-04-09 19:05:30 +00001277 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001278 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1279 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001280
Chris Lattner2eefe512004-04-09 19:05:30 +00001281 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1282 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001283 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1284 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001285 }
1286
1287 Value *Op0 = SO, *Op1 = ConstOperand;
1288 if (!ConstIsRHS)
1289 std::swap(Op0, Op1);
1290 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1292 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1293 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1294 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001295 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001296 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001297 abort();
1298 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001299 return IC->InsertNewInstBefore(New, I);
1300}
1301
1302// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1303// constant as the other operand, try to fold the binary operator into the
1304// select arguments. This also works for Cast instructions, which obviously do
1305// not have a second operand.
1306static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1307 InstCombiner *IC) {
1308 // Don't modify shared select instructions
1309 if (!SI->hasOneUse()) return 0;
1310 Value *TV = SI->getOperand(1);
1311 Value *FV = SI->getOperand(2);
1312
1313 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001314 // Bool selects with constant operands can be folded to logical ops.
1315 if (SI->getType() == Type::BoolTy) return 0;
1316
Chris Lattner6e7ba452005-01-01 16:22:27 +00001317 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1318 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1319
1320 return new SelectInst(SI->getCondition(), SelectTrueVal,
1321 SelectFalseVal);
1322 }
1323 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001324}
1325
Chris Lattner4e998b22004-09-29 05:07:12 +00001326
1327/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1328/// node as operand #0, see if we can fold the instruction into the PHI (which
1329/// is only possible if all operands to the PHI are constants).
1330Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1331 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001332 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001333 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001334
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001335 // Check to see if all of the operands of the PHI are constants. If there is
1336 // one non-constant value, remember the BB it is. If there is more than one
1337 // bail out.
1338 BasicBlock *NonConstBB = 0;
1339 for (unsigned i = 0; i != NumPHIValues; ++i)
1340 if (!isa<Constant>(PN->getIncomingValue(i))) {
1341 if (NonConstBB) return 0; // More than one non-const value.
1342 NonConstBB = PN->getIncomingBlock(i);
1343
1344 // If the incoming non-constant value is in I's block, we have an infinite
1345 // loop.
1346 if (NonConstBB == I.getParent())
1347 return 0;
1348 }
1349
1350 // If there is exactly one non-constant value, we can insert a copy of the
1351 // operation in that block. However, if this is a critical edge, we would be
1352 // inserting the computation one some other paths (e.g. inside a loop). Only
1353 // do this if the pred block is unconditionally branching into the phi block.
1354 if (NonConstBB) {
1355 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1356 if (!BI || !BI->isUnconditional()) return 0;
1357 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001358
1359 // Okay, we can do the transformation: create the new PHI node.
1360 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1361 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001362 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001363 InsertNewInstBefore(NewPN, *PN);
1364
1365 // Next, add all of the operands to the PHI.
1366 if (I.getNumOperands() == 2) {
1367 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001368 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001369 Value *InV;
1370 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1371 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1372 } else {
1373 assert(PN->getIncomingBlock(i) == NonConstBB);
1374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1375 InV = BinaryOperator::create(BO->getOpcode(),
1376 PN->getIncomingValue(i), C, "phitmp",
1377 NonConstBB->getTerminator());
1378 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1379 InV = new ShiftInst(SI->getOpcode(),
1380 PN->getIncomingValue(i), C, "phitmp",
1381 NonConstBB->getTerminator());
1382 else
1383 assert(0 && "Unknown binop!");
1384
1385 WorkList.push_back(cast<Instruction>(InV));
1386 }
1387 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001388 }
1389 } else {
1390 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1391 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001392 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001393 Value *InV;
1394 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1395 InV = ConstantExpr::getCast(InC, RetTy);
1396 } else {
1397 assert(PN->getIncomingBlock(i) == NonConstBB);
1398 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1399 NonConstBB->getTerminator());
1400 WorkList.push_back(cast<Instruction>(InV));
1401 }
1402 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001403 }
1404 }
1405 return ReplaceInstUsesWith(I, NewPN);
1406}
1407
Chris Lattner7e708292002-06-25 16:13:24 +00001408Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001409 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001410 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001411
Chris Lattner66331a42004-04-10 22:01:55 +00001412 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001413 // X + undef -> undef
1414 if (isa<UndefValue>(RHS))
1415 return ReplaceInstUsesWith(I, RHS);
1416
Chris Lattner66331a42004-04-10 22:01:55 +00001417 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001418 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1419 if (RHSC->isNullValue())
1420 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001421 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1422 if (CFP->isExactlyValue(-0.0))
1423 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001424 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001425
Chris Lattner66331a42004-04-10 22:01:55 +00001426 // X + (signbit) --> X ^ signbit
1427 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001428 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001429 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001430 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001431 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001432
1433 if (isa<PHINode>(LHS))
1434 if (Instruction *NV = FoldOpIntoPhi(I))
1435 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001436
Chris Lattner4f637d42006-01-06 17:59:59 +00001437 ConstantInt *XorRHS = 0;
1438 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001439 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1440 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1441 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1442 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1443
1444 uint64_t C0080Val = 1ULL << 31;
1445 int64_t CFF80Val = -C0080Val;
1446 unsigned Size = 32;
1447 do {
1448 if (TySizeBits > Size) {
1449 bool Found = false;
1450 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1451 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1452 if (RHSSExt == CFF80Val) {
1453 if (XorRHS->getZExtValue() == C0080Val)
1454 Found = true;
1455 } else if (RHSZExt == C0080Val) {
1456 if (XorRHS->getSExtValue() == CFF80Val)
1457 Found = true;
1458 }
1459 if (Found) {
1460 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001461 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001462 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001463 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001464 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001465 Size = 0; // Not a sign ext, but can't be any others either.
1466 goto FoundSExt;
1467 }
1468 }
1469 Size >>= 1;
1470 C0080Val >>= Size;
1471 CFF80Val >>= Size;
1472 } while (Size >= 8);
1473
1474FoundSExt:
1475 const Type *MiddleType = 0;
1476 switch (Size) {
1477 default: break;
1478 case 32: MiddleType = Type::IntTy; break;
1479 case 16: MiddleType = Type::ShortTy; break;
1480 case 8: MiddleType = Type::SByteTy; break;
1481 }
1482 if (MiddleType) {
1483 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1484 InsertNewInstBefore(NewTrunc, I);
1485 return new CastInst(NewTrunc, I.getType());
1486 }
1487 }
Chris Lattner66331a42004-04-10 22:01:55 +00001488 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001489
Chris Lattner564a7272003-08-13 19:01:45 +00001490 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001491 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001492 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001493
1494 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1495 if (RHSI->getOpcode() == Instruction::Sub)
1496 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1497 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1498 }
1499 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1500 if (LHSI->getOpcode() == Instruction::Sub)
1501 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1502 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1503 }
Robert Bocchino71698282004-07-27 21:02:21 +00001504 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001505
Chris Lattner5c4afb92002-05-08 22:46:53 +00001506 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001507 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001508 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001509
1510 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001511 if (!isa<Constant>(RHS))
1512 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001513 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001514
Misha Brukmanfd939082005-04-21 23:48:37 +00001515
Chris Lattner50af16a2004-11-13 19:50:12 +00001516 ConstantInt *C2;
1517 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1518 if (X == RHS) // X*C + X --> X * (C+1)
1519 return BinaryOperator::createMul(RHS, AddOne(C2));
1520
1521 // X*C1 + X*C2 --> X * (C1+C2)
1522 ConstantInt *C1;
1523 if (X == dyn_castFoldableMul(RHS, C1))
1524 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001525 }
1526
1527 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001528 if (dyn_castFoldableMul(RHS, C2) == LHS)
1529 return BinaryOperator::createMul(LHS, AddOne(C2));
1530
Chris Lattnerad3448c2003-02-18 19:57:07 +00001531
Chris Lattner564a7272003-08-13 19:01:45 +00001532 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001533 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001534 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001535
Chris Lattner6b032052003-10-02 15:11:26 +00001536 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001537 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001538 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1539 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1540 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001541 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001542
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001543 // (X & FF00) + xx00 -> (X+xx00) & FF00
1544 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1545 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1546 if (Anded == CRHS) {
1547 // See if all bits from the first bit set in the Add RHS up are included
1548 // in the mask. First, get the rightmost bit.
1549 uint64_t AddRHSV = CRHS->getRawValue();
1550
1551 // Form a mask of all bits from the lowest bit added through the top.
1552 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001553 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001554
1555 // See if the and mask includes all of these bits.
1556 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001557
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001558 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1559 // Okay, the xform is safe. Insert the new add pronto.
1560 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1561 LHS->getName()), I);
1562 return BinaryOperator::createAnd(NewAdd, C2);
1563 }
1564 }
1565 }
1566
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001567 // Try to fold constant add into select arguments.
1568 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001569 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001570 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001571 }
1572
Chris Lattner7e708292002-06-25 16:13:24 +00001573 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001574}
1575
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001576// isSignBit - Return true if the value represented by the constant only has the
1577// highest order bit set.
1578static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001579 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +00001580 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001581}
1582
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001583/// RemoveNoopCast - Strip off nonconverting casts from the value.
1584///
1585static Value *RemoveNoopCast(Value *V) {
1586 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1587 const Type *CTy = CI->getType();
1588 const Type *OpTy = CI->getOperand(0)->getType();
1589 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001590 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001591 return RemoveNoopCast(CI->getOperand(0));
1592 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1593 return RemoveNoopCast(CI->getOperand(0));
1594 }
1595 return V;
1596}
1597
Chris Lattner7e708292002-06-25 16:13:24 +00001598Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001599 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001600
Chris Lattner233f7dc2002-08-12 21:17:25 +00001601 if (Op0 == Op1) // sub X, X -> 0
1602 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001603
Chris Lattner233f7dc2002-08-12 21:17:25 +00001604 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001605 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001606 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001607
Chris Lattnere87597f2004-10-16 18:11:37 +00001608 if (isa<UndefValue>(Op0))
1609 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1610 if (isa<UndefValue>(Op1))
1611 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1612
Chris Lattnerd65460f2003-11-05 01:06:05 +00001613 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1614 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001615 if (C->isAllOnesValue())
1616 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001617
Chris Lattnerd65460f2003-11-05 01:06:05 +00001618 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001619 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001620 if (match(Op1, m_Not(m_Value(X))))
1621 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001622 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001623 // -((uint)X >> 31) -> ((int)X >> 31)
1624 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001625 if (C->isNullValue()) {
1626 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1627 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001628 if (SI->getOpcode() == Instruction::Shr)
1629 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1630 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001631 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001632 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001633 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001634 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001635 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001636 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001637 // Ok, the transformation is safe. Insert a cast of the incoming
1638 // value, then the new shift, then the new cast.
1639 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1640 SI->getOperand(0)->getName());
1641 Value *InV = InsertNewInstBefore(FirstCast, I);
1642 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1643 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001644 if (NewShift->getType() == I.getType())
1645 return NewShift;
1646 else {
1647 InV = InsertNewInstBefore(NewShift, I);
1648 return new CastInst(NewShift, I.getType());
1649 }
Chris Lattner9c290672004-03-12 23:53:13 +00001650 }
1651 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001652 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001653
1654 // Try to fold constant sub into select arguments.
1655 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001656 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001657 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001658
1659 if (isa<PHINode>(Op0))
1660 if (Instruction *NV = FoldOpIntoPhi(I))
1661 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001662 }
1663
Chris Lattner43d84d62005-04-07 16:15:25 +00001664 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1665 if (Op1I->getOpcode() == Instruction::Add &&
1666 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001667 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001668 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001669 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001670 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001671 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1672 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1673 // C1-(X+C2) --> (C1-C2)-X
1674 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1675 Op1I->getOperand(0));
1676 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001677 }
1678
Chris Lattnerfd059242003-10-15 16:48:29 +00001679 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001680 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1681 // is not used by anyone else...
1682 //
Chris Lattner0517e722004-02-02 20:09:56 +00001683 if (Op1I->getOpcode() == Instruction::Sub &&
1684 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001685 // Swap the two operands of the subexpr...
1686 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1687 Op1I->setOperand(0, IIOp1);
1688 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001689
Chris Lattnera2881962003-02-18 19:28:33 +00001690 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001691 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001692 }
1693
1694 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1695 //
1696 if (Op1I->getOpcode() == Instruction::And &&
1697 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1698 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1699
Chris Lattnerf523d062004-06-09 05:08:07 +00001700 Value *NewNot =
1701 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001702 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001703 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001704
Chris Lattner91ccc152004-10-06 15:08:25 +00001705 // -(X sdiv C) -> (X sdiv -C)
1706 if (Op1I->getOpcode() == Instruction::Div)
1707 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001708 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001709 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001710 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001711 ConstantExpr::getNeg(DivRHS));
1712
Chris Lattnerad3448c2003-02-18 19:57:07 +00001713 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001714 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001715 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001716 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001717 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001718 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001719 }
Chris Lattner40371712002-05-09 01:29:19 +00001720 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001721 }
Chris Lattnera2881962003-02-18 19:28:33 +00001722
Chris Lattner7edc8c22005-04-07 17:14:51 +00001723 if (!Op0->getType()->isFloatingPoint())
1724 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1725 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001726 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1727 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1728 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1729 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001730 } else if (Op0I->getOpcode() == Instruction::Sub) {
1731 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1732 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001733 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001734
Chris Lattner50af16a2004-11-13 19:50:12 +00001735 ConstantInt *C1;
1736 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1737 if (X == Op1) { // X*C - X --> X * (C-1)
1738 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1739 return BinaryOperator::createMul(Op1, CP1);
1740 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001741
Chris Lattner50af16a2004-11-13 19:50:12 +00001742 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1743 if (X == dyn_castFoldableMul(Op1, C2))
1744 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1745 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001746 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001747}
1748
Chris Lattner4cb170c2004-02-23 06:38:22 +00001749/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1750/// really just returns true if the most significant (sign) bit is set.
1751static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1752 if (RHS->getType()->isSigned()) {
1753 // True if source is LHS < 0 or LHS <= -1
1754 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1755 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1756 } else {
1757 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1758 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1759 // the size of the integer type.
1760 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001761 return RHSC->getValue() ==
1762 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001763 if (Opcode == Instruction::SetGT)
1764 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001765 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001766 }
1767 return false;
1768}
1769
Chris Lattner7e708292002-06-25 16:13:24 +00001770Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001771 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001772 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001773
Chris Lattnere87597f2004-10-16 18:11:37 +00001774 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1775 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1776
Chris Lattner233f7dc2002-08-12 21:17:25 +00001777 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001778 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1779 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001780
1781 // ((X << C1)*C2) == (X * (C2 << C1))
1782 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1783 if (SI->getOpcode() == Instruction::Shl)
1784 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001785 return BinaryOperator::createMul(SI->getOperand(0),
1786 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001787
Chris Lattner515c97c2003-09-11 22:24:54 +00001788 if (CI->isNullValue())
1789 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1790 if (CI->equalsInt(1)) // X * 1 == X
1791 return ReplaceInstUsesWith(I, Op0);
1792 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001793 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001794
Chris Lattner515c97c2003-09-11 22:24:54 +00001795 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001796 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1797 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001798 return new ShiftInst(Instruction::Shl, Op0,
1799 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001800 }
Robert Bocchino71698282004-07-27 21:02:21 +00001801 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001802 if (Op1F->isNullValue())
1803 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001804
Chris Lattnera2881962003-02-18 19:28:33 +00001805 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1806 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1807 if (Op1F->getValue() == 1.0)
1808 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1809 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001810
1811 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1812 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1813 isa<ConstantInt>(Op0I->getOperand(1))) {
1814 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1815 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1816 Op1, "tmp");
1817 InsertNewInstBefore(Add, I);
1818 Value *C1C2 = ConstantExpr::getMul(Op1,
1819 cast<Constant>(Op0I->getOperand(1)));
1820 return BinaryOperator::createAdd(Add, C1C2);
1821
1822 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001823
1824 // Try to fold constant mul into select arguments.
1825 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001826 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001827 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001828
1829 if (isa<PHINode>(Op0))
1830 if (Instruction *NV = FoldOpIntoPhi(I))
1831 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001832 }
1833
Chris Lattnera4f445b2003-03-10 23:23:04 +00001834 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1835 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001836 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001837
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001838 // If one of the operands of the multiply is a cast from a boolean value, then
1839 // we know the bool is either zero or one, so this is a 'masking' multiply.
1840 // See if we can simplify things based on how the boolean was originally
1841 // formed.
1842 CastInst *BoolCast = 0;
1843 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1844 if (CI->getOperand(0)->getType() == Type::BoolTy)
1845 BoolCast = CI;
1846 if (!BoolCast)
1847 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1848 if (CI->getOperand(0)->getType() == Type::BoolTy)
1849 BoolCast = CI;
1850 if (BoolCast) {
1851 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1852 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1853 const Type *SCOpTy = SCIOp0->getType();
1854
Chris Lattner4cb170c2004-02-23 06:38:22 +00001855 // If the setcc is true iff the sign bit of X is set, then convert this
1856 // multiply into a shift/and combination.
1857 if (isa<ConstantInt>(SCIOp1) &&
1858 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001859 // Shift the X value right to turn it into "all signbits".
1860 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001861 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001862 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001863 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001864 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1865 SCIOp0->getName()), I);
1866 }
1867
1868 Value *V =
1869 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1870 BoolCast->getOperand(0)->getName()+
1871 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001872
1873 // If the multiply type is not the same as the source type, sign extend
1874 // or truncate to the multiply type.
1875 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001876 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001877
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001878 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001879 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001880 }
1881 }
1882 }
1883
Chris Lattner7e708292002-06-25 16:13:24 +00001884 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001885}
1886
Chris Lattner7e708292002-06-25 16:13:24 +00001887Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001889
Chris Lattner857e8cd2004-12-12 21:48:58 +00001890 if (isa<UndefValue>(Op0)) // undef / X -> 0
1891 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1892 if (isa<UndefValue>(Op1))
1893 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1894
1895 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001896 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001897 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001898 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001899
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001900 // div X, -1 == -X
1901 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001902 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001903
Chris Lattner857e8cd2004-12-12 21:48:58 +00001904 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001905 if (LHS->getOpcode() == Instruction::Div)
1906 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001907 // (X / C1) / C2 -> X / (C1*C2)
1908 return BinaryOperator::createDiv(LHS->getOperand(0),
1909 ConstantExpr::getMul(RHS, LHSRHS));
1910 }
1911
Chris Lattnera2881962003-02-18 19:28:33 +00001912 // Check to see if this is an unsigned division with an exact power of 2,
1913 // if so, convert to a right shift.
1914 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1915 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001916 if (isPowerOf2_64(Val)) {
1917 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001918 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001919 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001920 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001921
Chris Lattnera052f822004-10-09 02:50:40 +00001922 // -X/C -> X/-C
1923 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001924 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001925 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1926
Chris Lattner857e8cd2004-12-12 21:48:58 +00001927 if (!RHS->isNullValue()) {
1928 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001929 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001930 return R;
1931 if (isa<PHINode>(Op0))
1932 if (Instruction *NV = FoldOpIntoPhi(I))
1933 return NV;
1934 }
Chris Lattnera2881962003-02-18 19:28:33 +00001935 }
1936
Chris Lattner8e49e082006-09-09 20:26:32 +00001937 // Handle div X, Cond?Y:Z
1938 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1939 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1940 // same basic block, then we replace the select with Y, and the condition of
1941 // the select with false (if the cond value is in the same BB). If the
1942 // select has uses other than the div, this allows them to be simplified
1943 // also.
1944 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1945 if (ST->isNullValue()) {
1946 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1947 if (CondI && CondI->getParent() == I.getParent())
1948 UpdateValueUsesWith(CondI, ConstantBool::False);
1949 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1950 I.setOperand(1, SI->getOperand(2));
1951 else
1952 UpdateValueUsesWith(SI, SI->getOperand(2));
1953 return &I;
1954 }
1955 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
1956 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1957 if (ST->isNullValue()) {
1958 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1959 if (CondI && CondI->getParent() == I.getParent())
1960 UpdateValueUsesWith(CondI, ConstantBool::True);
1961 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1962 I.setOperand(1, SI->getOperand(1));
1963 else
1964 UpdateValueUsesWith(SI, SI->getOperand(1));
1965 return &I;
1966 }
1967
1968 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1969 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattner857e8cd2004-12-12 21:48:58 +00001970 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1971 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattner8e49e082006-09-09 20:26:32 +00001972 // STO == 0 and SFO == 0 handled above.
Chris Lattnerbf70b832005-04-08 04:03:26 +00001973 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001974 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1975 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001976 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1977 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1978 TC, SI->getName()+".t");
1979 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001980
Chris Lattnerbf70b832005-04-08 04:03:26 +00001981 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1982 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1983 FC, SI->getName()+".f");
1984 FSI = InsertNewInstBefore(FSI, I);
1985 return new SelectInst(SI->getOperand(0), TSI, FSI);
1986 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001987 }
Chris Lattner8e49e082006-09-09 20:26:32 +00001988 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001989
Chris Lattnera2881962003-02-18 19:28:33 +00001990 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001991 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001992 if (LHS->equalsInt(0))
1993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1994
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001995 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001996 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001997 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001998 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1999 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002000 const Type *NTy = Op0->getType()->getUnsignedVersion();
2001 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2002 InsertNewInstBefore(LHS, I);
2003 Value *RHS;
2004 if (Constant *R = dyn_cast<Constant>(Op1))
2005 RHS = ConstantExpr::getCast(R, NTy);
2006 else
2007 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2008 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2009 InsertNewInstBefore(Div, I);
2010 return new CastInst(Div, I.getType());
2011 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002012 } else {
2013 // Known to be an unsigned division.
2014 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2015 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2016 if (RHSI->getOpcode() == Instruction::Shl &&
2017 isa<ConstantUInt>(RHSI->getOperand(0))) {
2018 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2019 if (isPowerOf2_64(C1)) {
2020 unsigned C2 = Log2_64(C1);
2021 Value *Add = RHSI->getOperand(1);
2022 if (C2) {
2023 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2024 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2025 "tmp"), I);
2026 }
2027 return new ShiftInst(Instruction::Shr, Op0, Add);
2028 }
2029 }
2030 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002031 }
2032
Chris Lattner3f5b8772002-05-06 16:14:14 +00002033 return 0;
2034}
2035
2036
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002037/// GetFactor - If we can prove that the specified value is at least a multiple
2038/// of some factor, return that factor.
2039static Constant *GetFactor(Value *V) {
2040 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2041 return CI;
2042
2043 // Unless we can be tricky, we know this is a multiple of 1.
2044 Constant *Result = ConstantInt::get(V->getType(), 1);
2045
2046 Instruction *I = dyn_cast<Instruction>(V);
2047 if (!I) return Result;
2048
2049 if (I->getOpcode() == Instruction::Mul) {
2050 // Handle multiplies by a constant, etc.
2051 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2052 GetFactor(I->getOperand(1)));
2053 } else if (I->getOpcode() == Instruction::Shl) {
2054 // (X<<C) -> X * (1 << C)
2055 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2056 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2057 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2058 }
2059 } else if (I->getOpcode() == Instruction::And) {
2060 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2061 // X & 0xFFF0 is known to be a multiple of 16.
2062 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2063 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2064 return ConstantExpr::getShl(Result,
2065 ConstantUInt::get(Type::UByteTy, Zeros));
2066 }
2067 } else if (I->getOpcode() == Instruction::Cast) {
2068 Value *Op = I->getOperand(0);
2069 // Only handle int->int casts.
2070 if (!Op->getType()->isInteger()) return Result;
2071 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2072 }
2073 return Result;
2074}
2075
Chris Lattner7e708292002-06-25 16:13:24 +00002076Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002077 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002078
2079 // 0 % X == 0, we don't need to preserve faults!
2080 if (Constant *LHS = dyn_cast<Constant>(Op0))
2081 if (LHS->isNullValue())
2082 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2083
2084 if (isa<UndefValue>(Op0)) // undef % X -> 0
2085 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2086 if (isa<UndefValue>(Op1))
2087 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2088
Chris Lattner11a49f22005-11-05 07:28:37 +00002089 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002090 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00002091 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00002092 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00002093 // X % -Y -> X % Y
2094 AddUsesToWorkList(I);
2095 I.setOperand(1, RHSNeg);
2096 return &I;
2097 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002098
2099 // If the top bits of both operands are zero (i.e. we can prove they are
2100 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002101 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2102 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00002103 const Type *NTy = Op0->getType()->getUnsignedVersion();
2104 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2105 InsertNewInstBefore(LHS, I);
2106 Value *RHS;
2107 if (Constant *R = dyn_cast<Constant>(Op1))
2108 RHS = ConstantExpr::getCast(R, NTy);
2109 else
2110 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2111 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2112 InsertNewInstBefore(Rem, I);
2113 return new CastInst(Rem, I.getType());
2114 }
2115 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002116
Chris Lattner857e8cd2004-12-12 21:48:58 +00002117 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002118 // X % 0 == undef, we don't need to preserve faults!
2119 if (RHS->equalsInt(0))
2120 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2121
Chris Lattnera2881962003-02-18 19:28:33 +00002122 if (RHS->equalsInt(1)) // X % 1 == 0
2123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2124
2125 // Check to see if this is an unsigned remainder with an exact power of 2,
2126 // if so, convert to a bitwise and.
2127 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002128 if (isPowerOf2_64(C->getValue()))
2129 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattner857e8cd2004-12-12 21:48:58 +00002130
Chris Lattner97943922006-02-28 05:49:21 +00002131 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2132 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2133 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2134 return R;
2135 } else if (isa<PHINode>(Op0I)) {
2136 if (Instruction *NV = FoldOpIntoPhi(I))
2137 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002138 }
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002139
2140 // X*C1%C2 --> 0 iff C1%C2 == 0
2141 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2142 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002143 }
Chris Lattnera2881962003-02-18 19:28:33 +00002144 }
2145
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002146 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2147 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2148 if (I.getType()->isUnsigned() &&
2149 RHSI->getOpcode() == Instruction::Shl &&
2150 isa<ConstantUInt>(RHSI->getOperand(0))) {
2151 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2152 if (isPowerOf2_64(C1)) {
2153 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2154 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2155 "tmp"), I);
2156 return BinaryOperator::createAnd(Op0, Add);
2157 }
2158 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002159
2160 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2161 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattner8e49e082006-09-09 20:26:32 +00002162 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2163 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2164 // the same basic block, then we replace the select with Y, and the
2165 // condition of the select with false (if the cond value is in the same
2166 // BB). If the select has uses other than the div, this allows them to be
2167 // simplified also.
2168 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2169 if (ST->isNullValue()) {
2170 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2171 if (CondI && CondI->getParent() == I.getParent())
2172 UpdateValueUsesWith(CondI, ConstantBool::False);
2173 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2174 I.setOperand(1, SI->getOperand(2));
2175 else
2176 UpdateValueUsesWith(SI, SI->getOperand(2));
2177 return &I;
2178 }
2179 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2180 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2181 if (ST->isNullValue()) {
2182 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2183 if (CondI && CondI->getParent() == I.getParent())
2184 UpdateValueUsesWith(CondI, ConstantBool::True);
2185 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2186 I.setOperand(1, SI->getOperand(1));
2187 else
2188 UpdateValueUsesWith(SI, SI->getOperand(1));
2189 return &I;
2190 }
2191
2192
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002193 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2194 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattner8e49e082006-09-09 20:26:32 +00002195 // STO == 0 and SFO == 0 handled above.
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002196
2197 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2198 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2199 SubOne(STO), SI->getName()+".t"), I);
2200 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2201 SubOne(SFO), SI->getName()+".f"), I);
2202 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2203 }
2204 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002205 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002206 }
2207
Chris Lattner3f5b8772002-05-06 16:14:14 +00002208 return 0;
2209}
2210
Chris Lattner8b170942002-08-09 23:47:40 +00002211// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002212static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00002213 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2214 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002215
2216 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002217
Chris Lattner8b170942002-08-09 23:47:40 +00002218 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00002219 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002220 int64_t Val = INT64_MAX; // All ones
2221 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2222 return CS->getValue() == Val-1;
2223}
2224
2225// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002226static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00002227 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2228 return CU->getValue() == 1;
2229
2230 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002231
2232 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002233 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002234 int64_t Val = -1; // All ones
2235 Val <<= TypeBits-1; // Shift over to the right spot
2236 return CS->getValue() == Val+1;
2237}
2238
Chris Lattner457dd822004-06-09 07:59:58 +00002239// isOneBitSet - Return true if there is exactly one bit set in the specified
2240// constant.
2241static bool isOneBitSet(const ConstantInt *CI) {
2242 uint64_t V = CI->getRawValue();
2243 return V && (V & (V-1)) == 0;
2244}
2245
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002246#if 0 // Currently unused
2247// isLowOnes - Return true if the constant is of the form 0+1+.
2248static bool isLowOnes(const ConstantInt *CI) {
2249 uint64_t V = CI->getRawValue();
2250
2251 // There won't be bits set in parts that the type doesn't contain.
2252 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2253
2254 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2255 return U && V && (U & V) == 0;
2256}
2257#endif
2258
2259// isHighOnes - Return true if the constant is of the form 1+0+.
2260// This is the same as lowones(~X).
2261static bool isHighOnes(const ConstantInt *CI) {
2262 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002263 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002264
2265 // There won't be bits set in parts that the type doesn't contain.
2266 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2267
2268 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2269 return U && V && (U & V) == 0;
2270}
2271
2272
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002273/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2274/// are carefully arranged to allow folding of expressions such as:
2275///
2276/// (A < B) | (A > B) --> (A != B)
2277///
2278/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2279/// represents that the comparison is true if A == B, and bit value '1' is true
2280/// if A < B.
2281///
2282static unsigned getSetCondCode(const SetCondInst *SCI) {
2283 switch (SCI->getOpcode()) {
2284 // False -> 0
2285 case Instruction::SetGT: return 1;
2286 case Instruction::SetEQ: return 2;
2287 case Instruction::SetGE: return 3;
2288 case Instruction::SetLT: return 4;
2289 case Instruction::SetNE: return 5;
2290 case Instruction::SetLE: return 6;
2291 // True -> 7
2292 default:
2293 assert(0 && "Invalid SetCC opcode!");
2294 return 0;
2295 }
2296}
2297
2298/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2299/// opcode and two operands into either a constant true or false, or a brand new
2300/// SetCC instruction.
2301static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2302 switch (Opcode) {
2303 case 0: return ConstantBool::False;
2304 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2305 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2306 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2307 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2308 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2309 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2310 case 7: return ConstantBool::True;
2311 default: assert(0 && "Illegal SetCCCode!"); return 0;
2312 }
2313}
2314
2315// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2316struct FoldSetCCLogical {
2317 InstCombiner &IC;
2318 Value *LHS, *RHS;
2319 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2320 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2321 bool shouldApply(Value *V) const {
2322 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2323 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2324 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2325 return false;
2326 }
2327 Instruction *apply(BinaryOperator &Log) const {
2328 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2329 if (SCI->getOperand(0) != LHS) {
2330 assert(SCI->getOperand(1) == LHS);
2331 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2332 }
2333
2334 unsigned LHSCode = getSetCondCode(SCI);
2335 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2336 unsigned Code;
2337 switch (Log.getOpcode()) {
2338 case Instruction::And: Code = LHSCode & RHSCode; break;
2339 case Instruction::Or: Code = LHSCode | RHSCode; break;
2340 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002341 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002342 }
2343
2344 Value *RV = getSetCCValue(Code, LHS, RHS);
2345 if (Instruction *I = dyn_cast<Instruction>(RV))
2346 return I;
2347 // Otherwise, it's a constant boolean value...
2348 return IC.ReplaceInstUsesWith(Log, RV);
2349 }
2350};
2351
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002352// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2353// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2354// guaranteed to be either a shift instruction or a binary operator.
2355Instruction *InstCombiner::OptAndOp(Instruction *Op,
2356 ConstantIntegral *OpRHS,
2357 ConstantIntegral *AndRHS,
2358 BinaryOperator &TheAnd) {
2359 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002360 Constant *Together = 0;
2361 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002362 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002363
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002364 switch (Op->getOpcode()) {
2365 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002366 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002367 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2368 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002369 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002370 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002371 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002372 }
2373 break;
2374 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002375 if (Together == AndRHS) // (X | C) & C --> C
2376 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002377
Chris Lattner6e7ba452005-01-01 16:22:27 +00002378 if (Op->hasOneUse() && Together != OpRHS) {
2379 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2380 std::string Op0Name = Op->getName(); Op->setName("");
2381 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2382 InsertNewInstBefore(Or, TheAnd);
2383 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002384 }
2385 break;
2386 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002387 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002388 // Adding a one to a single bit bit-field should be turned into an XOR
2389 // of the bit. First thing to check is to see if this AND is with a
2390 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00002391 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002392
2393 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002394 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002395
2396 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002397 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002398 // Ok, at this point, we know that we are masking the result of the
2399 // ADD down to exactly one bit. If the constant we are adding has
2400 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00002401 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002402
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002403 // Check to see if any bits below the one bit set in AndRHSV are set.
2404 if ((AddRHS & (AndRHSV-1)) == 0) {
2405 // If not, the only thing that can effect the output of the AND is
2406 // the bit specified by AndRHSV. If that bit is set, the effect of
2407 // the XOR is to toggle the bit. If it is clear, then the ADD has
2408 // no effect.
2409 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2410 TheAnd.setOperand(0, X);
2411 return &TheAnd;
2412 } else {
2413 std::string Name = Op->getName(); Op->setName("");
2414 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002415 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002416 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002417 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002418 }
2419 }
2420 }
2421 }
2422 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002423
2424 case Instruction::Shl: {
2425 // We know that the AND will not produce any of the bits shifted in, so if
2426 // the anded constant includes them, clear them now!
2427 //
2428 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002429 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2430 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002431
Chris Lattner0c967662004-09-24 15:21:34 +00002432 if (CI == ShlMask) { // Masking out bits that the shift already masks
2433 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2434 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002435 TheAnd.setOperand(1, CI);
2436 return &TheAnd;
2437 }
2438 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002439 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002440 case Instruction::Shr:
2441 // We know that the AND will not produce any of the bits shifted in, so if
2442 // the anded constant includes them, clear them now! This only applies to
2443 // unsigned shifts, because a signed shr may bring in set bits!
2444 //
2445 if (AndRHS->getType()->isUnsigned()) {
2446 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002447 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2448 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2449
2450 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2451 return ReplaceInstUsesWith(TheAnd, Op);
2452 } else if (CI != AndRHS) {
2453 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002454 return &TheAnd;
2455 }
Chris Lattner0c967662004-09-24 15:21:34 +00002456 } else { // Signed shr.
2457 // See if this is shifting in some sign extension, then masking it out
2458 // with an and.
2459 if (Op->hasOneUse()) {
2460 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2461 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2462 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002463 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002464 // Make the argument unsigned.
2465 Value *ShVal = Op->getOperand(0);
2466 ShVal = InsertCastBefore(ShVal,
2467 ShVal->getType()->getUnsignedVersion(),
2468 TheAnd);
2469 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2470 OpRHS, Op->getName()),
2471 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002472 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2473 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2474 TheAnd.getName()),
2475 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002476 return new CastInst(ShVal, Op->getType());
2477 }
2478 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002479 }
2480 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002481 }
2482 return 0;
2483}
2484
Chris Lattner8b170942002-08-09 23:47:40 +00002485
Chris Lattnera96879a2004-09-29 17:40:11 +00002486/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2487/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2488/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2489/// insert new instructions.
2490Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2491 bool Inside, Instruction &IB) {
2492 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2493 "Lo is not <= Hi in range emission code!");
2494 if (Inside) {
2495 if (Lo == Hi) // Trivially false.
2496 return new SetCondInst(Instruction::SetNE, V, V);
2497 if (cast<ConstantIntegral>(Lo)->isMinValue())
2498 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002499
Chris Lattnera96879a2004-09-29 17:40:11 +00002500 Constant *AddCST = ConstantExpr::getNeg(Lo);
2501 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2502 InsertNewInstBefore(Add, IB);
2503 // Convert to unsigned for the comparison.
2504 const Type *UnsType = Add->getType()->getUnsignedVersion();
2505 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2506 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2507 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2508 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2509 }
2510
2511 if (Lo == Hi) // Trivially true.
2512 return new SetCondInst(Instruction::SetEQ, V, V);
2513
2514 Hi = SubOne(cast<ConstantInt>(Hi));
2515 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2516 return new SetCondInst(Instruction::SetGT, V, Hi);
2517
2518 // Emit X-Lo > Hi-Lo-1
2519 Constant *AddCST = ConstantExpr::getNeg(Lo);
2520 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2521 InsertNewInstBefore(Add, IB);
2522 // Convert to unsigned for the comparison.
2523 const Type *UnsType = Add->getType()->getUnsignedVersion();
2524 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2525 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2526 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2527 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2528}
2529
Chris Lattner7203e152005-09-18 07:22:02 +00002530// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2531// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2532// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2533// not, since all 1s are not contiguous.
2534static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2535 uint64_t V = Val->getRawValue();
2536 if (!isShiftedMask_64(V)) return false;
2537
2538 // look for the first zero bit after the run of ones
2539 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2540 // look for the first non-zero bit
2541 ME = 64-CountLeadingZeros_64(V);
2542 return true;
2543}
2544
2545
2546
2547/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2548/// where isSub determines whether the operator is a sub. If we can fold one of
2549/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002550///
2551/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2552/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2553/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2554///
2555/// return (A +/- B).
2556///
2557Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2558 ConstantIntegral *Mask, bool isSub,
2559 Instruction &I) {
2560 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2561 if (!LHSI || LHSI->getNumOperands() != 2 ||
2562 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2563
2564 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2565
2566 switch (LHSI->getOpcode()) {
2567 default: return 0;
2568 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002569 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2570 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2571 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2572 break;
2573
2574 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2575 // part, we don't need any explicit masks to take them out of A. If that
2576 // is all N is, ignore it.
2577 unsigned MB, ME;
2578 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002579 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2580 Mask >>= 64-MB+1;
2581 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002582 break;
2583 }
2584 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002585 return 0;
2586 case Instruction::Or:
2587 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002588 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2589 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2590 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002591 break;
2592 return 0;
2593 }
2594
2595 Instruction *New;
2596 if (isSub)
2597 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2598 else
2599 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2600 return InsertNewInstBefore(New, I);
2601}
2602
Chris Lattner7e708292002-06-25 16:13:24 +00002603Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002604 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002606
Chris Lattnere87597f2004-10-16 18:11:37 +00002607 if (isa<UndefValue>(Op1)) // X & undef -> 0
2608 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2609
Chris Lattner6e7ba452005-01-01 16:22:27 +00002610 // and X, X = X
2611 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002612 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002613
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002614 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002615 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002616 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002617 if (!isa<PackedType>(I.getType()) &&
2618 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002619 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002620 return &I;
2621
Chris Lattner6e7ba452005-01-01 16:22:27 +00002622 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002623 uint64_t AndRHSMask = AndRHS->getZExtValue();
2624 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002625 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002626
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002627 // Optimize a variety of ((val OP C1) & C2) combinations...
2628 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2629 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002630 Value *Op0LHS = Op0I->getOperand(0);
2631 Value *Op0RHS = Op0I->getOperand(1);
2632 switch (Op0I->getOpcode()) {
2633 case Instruction::Xor:
2634 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002635 // If the mask is only needed on one incoming arm, push it up.
2636 if (Op0I->hasOneUse()) {
2637 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2638 // Not masking anything out for the LHS, move to RHS.
2639 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2640 Op0RHS->getName()+".masked");
2641 InsertNewInstBefore(NewRHS, I);
2642 return BinaryOperator::create(
2643 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002644 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00002645 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00002646 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2647 // Not masking anything out for the RHS, move to LHS.
2648 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2649 Op0LHS->getName()+".masked");
2650 InsertNewInstBefore(NewLHS, I);
2651 return BinaryOperator::create(
2652 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2653 }
2654 }
2655
Chris Lattner6e7ba452005-01-01 16:22:27 +00002656 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002657 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002658 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2659 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2660 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2661 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2662 return BinaryOperator::createAnd(V, AndRHS);
2663 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2664 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002665 break;
2666
2667 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002668 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2669 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2670 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2671 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2672 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002673 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002674 }
2675
Chris Lattner58403262003-07-23 19:25:52 +00002676 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002677 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002678 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002679 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2680 const Type *SrcTy = CI->getOperand(0)->getType();
2681
Chris Lattner2b83af22005-08-07 07:03:10 +00002682 // If this is an integer truncation or change from signed-to-unsigned, and
2683 // if the source is an and/or with immediate, transform it. This
2684 // frequently occurs for bitfield accesses.
2685 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2686 if (SrcTy->getPrimitiveSizeInBits() >=
2687 I.getType()->getPrimitiveSizeInBits() &&
2688 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00002689 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00002690 if (CastOp->getOpcode() == Instruction::And) {
2691 // Change: and (cast (and X, C1) to T), C2
2692 // into : and (cast X to T), trunc(C1)&C2
2693 // This will folds the two ands together, which may allow other
2694 // simplifications.
2695 Instruction *NewCast =
2696 new CastInst(CastOp->getOperand(0), I.getType(),
2697 CastOp->getName()+".shrunk");
2698 NewCast = InsertNewInstBefore(NewCast, I);
2699
2700 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2701 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2702 return BinaryOperator::createAnd(NewCast, C3);
2703 } else if (CastOp->getOpcode() == Instruction::Or) {
2704 // Change: and (cast (or X, C1) to T), C2
2705 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2706 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2707 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2708 return ReplaceInstUsesWith(I, AndRHS);
2709 }
2710 }
Chris Lattner06782f82003-07-23 19:36:21 +00002711 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002712
2713 // Try to fold constant and into select arguments.
2714 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002715 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002716 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002717 if (isa<PHINode>(Op0))
2718 if (Instruction *NV = FoldOpIntoPhi(I))
2719 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002720 }
2721
Chris Lattner8d969642003-03-10 23:06:50 +00002722 Value *Op0NotVal = dyn_castNotVal(Op0);
2723 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002724
Chris Lattner5b62aa72004-06-18 06:07:51 +00002725 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2726 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2727
Misha Brukmancb6267b2004-07-30 12:50:08 +00002728 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002729 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002730 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2731 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002732 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002733 return BinaryOperator::createNot(Or);
2734 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002735
2736 {
2737 Value *A = 0, *B = 0;
2738 ConstantInt *C1 = 0, *C2 = 0;
2739 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2740 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2741 return ReplaceInstUsesWith(I, Op1);
2742 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2743 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2744 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00002745
2746 if (Op0->hasOneUse() &&
2747 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2748 if (A == Op1) { // (A^B)&A -> A&(A^B)
2749 I.swapOperands(); // Simplify below
2750 std::swap(Op0, Op1);
2751 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2752 cast<BinaryOperator>(Op0)->swapOperands();
2753 I.swapOperands(); // Simplify below
2754 std::swap(Op0, Op1);
2755 }
2756 }
2757 if (Op1->hasOneUse() &&
2758 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2759 if (B == Op0) { // B&(A^B) -> B&(B^A)
2760 cast<BinaryOperator>(Op1)->swapOperands();
2761 std::swap(A, B);
2762 }
2763 if (A == Op0) { // A&(A^B) -> A & ~B
2764 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2765 InsertNewInstBefore(NotB, I);
2766 return BinaryOperator::createAnd(A, NotB);
2767 }
2768 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002769 }
2770
Chris Lattnera2881962003-02-18 19:28:33 +00002771
Chris Lattner955f3312004-09-28 21:48:02 +00002772 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2773 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002774 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2775 return R;
2776
Chris Lattner955f3312004-09-28 21:48:02 +00002777 Value *LHSVal, *RHSVal;
2778 ConstantInt *LHSCst, *RHSCst;
2779 Instruction::BinaryOps LHSCC, RHSCC;
2780 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2781 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2782 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2783 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002784 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002785 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2786 // Ensure that the larger constant is on the RHS.
2787 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2788 SetCondInst *LHS = cast<SetCondInst>(Op0);
2789 if (cast<ConstantBool>(Cmp)->getValue()) {
2790 std::swap(LHS, RHS);
2791 std::swap(LHSCst, RHSCst);
2792 std::swap(LHSCC, RHSCC);
2793 }
2794
2795 // At this point, we know we have have two setcc instructions
2796 // comparing a value against two constants and and'ing the result
2797 // together. Because of the above check, we know that we only have
2798 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2799 // FoldSetCCLogical check above), that the two constants are not
2800 // equal.
2801 assert(LHSCst != RHSCst && "Compares not folded above?");
2802
2803 switch (LHSCC) {
2804 default: assert(0 && "Unknown integer condition code!");
2805 case Instruction::SetEQ:
2806 switch (RHSCC) {
2807 default: assert(0 && "Unknown integer condition code!");
2808 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2809 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2810 return ReplaceInstUsesWith(I, ConstantBool::False);
2811 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2812 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2813 return ReplaceInstUsesWith(I, LHS);
2814 }
2815 case Instruction::SetNE:
2816 switch (RHSCC) {
2817 default: assert(0 && "Unknown integer condition code!");
2818 case Instruction::SetLT:
2819 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2820 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2821 break; // (X != 13 & X < 15) -> no change
2822 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2823 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2824 return ReplaceInstUsesWith(I, RHS);
2825 case Instruction::SetNE:
2826 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2827 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2828 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2829 LHSVal->getName()+".off");
2830 InsertNewInstBefore(Add, I);
2831 const Type *UnsType = Add->getType()->getUnsignedVersion();
2832 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2833 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2834 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2835 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2836 }
2837 break; // (X != 13 & X != 15) -> no change
2838 }
2839 break;
2840 case Instruction::SetLT:
2841 switch (RHSCC) {
2842 default: assert(0 && "Unknown integer condition code!");
2843 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2844 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2845 return ReplaceInstUsesWith(I, ConstantBool::False);
2846 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2847 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2848 return ReplaceInstUsesWith(I, LHS);
2849 }
2850 case Instruction::SetGT:
2851 switch (RHSCC) {
2852 default: assert(0 && "Unknown integer condition code!");
2853 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2854 return ReplaceInstUsesWith(I, LHS);
2855 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2856 return ReplaceInstUsesWith(I, RHS);
2857 case Instruction::SetNE:
2858 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2859 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2860 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002861 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2862 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002863 }
2864 }
2865 }
2866 }
2867
Chris Lattner6fc205f2006-05-05 06:39:07 +00002868 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2869 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00002870 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00002871 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00002872 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00002873 // Only do this if the casts both really cause code to be generated.
2874 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2875 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002876 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2877 Op1C->getOperand(0),
2878 I.getName());
2879 InsertNewInstBefore(NewOp, I);
2880 return new CastInst(NewOp, I.getType());
2881 }
2882 }
2883
Chris Lattner7e708292002-06-25 16:13:24 +00002884 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002885}
2886
Chris Lattnerafe91a52006-06-15 19:07:26 +00002887/// CollectBSwapParts - Look to see if the specified value defines a single byte
2888/// in the result. If it does, and if the specified byte hasn't been filled in
2889/// yet, fill it in and return false.
2890static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2891 Instruction *I = dyn_cast<Instruction>(V);
2892 if (I == 0) return true;
2893
2894 // If this is an or instruction, it is an inner node of the bswap.
2895 if (I->getOpcode() == Instruction::Or)
2896 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2897 CollectBSwapParts(I->getOperand(1), ByteValues);
2898
2899 // If this is a shift by a constant int, and it is "24", then its operand
2900 // defines a byte. We only handle unsigned types here.
2901 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2902 // Not shifting the entire input by N-1 bytes?
2903 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2904 8*(ByteValues.size()-1))
2905 return true;
2906
2907 unsigned DestNo;
2908 if (I->getOpcode() == Instruction::Shl) {
2909 // X << 24 defines the top byte with the lowest of the input bytes.
2910 DestNo = ByteValues.size()-1;
2911 } else {
2912 // X >>u 24 defines the low byte with the highest of the input bytes.
2913 DestNo = 0;
2914 }
2915
2916 // If the destination byte value is already defined, the values are or'd
2917 // together, which isn't a bswap (unless it's an or of the same bits).
2918 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2919 return true;
2920 ByteValues[DestNo] = I->getOperand(0);
2921 return false;
2922 }
2923
2924 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2925 // don't have this.
2926 Value *Shift = 0, *ShiftLHS = 0;
2927 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2928 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2929 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2930 return true;
2931 Instruction *SI = cast<Instruction>(Shift);
2932
2933 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2934 if (ShiftAmt->getRawValue() & 7 ||
2935 ShiftAmt->getRawValue() > 8*ByteValues.size())
2936 return true;
2937
2938 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2939 unsigned DestByte;
2940 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2941 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2942 break;
2943 // Unknown mask for bswap.
2944 if (DestByte == ByteValues.size()) return true;
2945
2946 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2947 unsigned SrcByte;
2948 if (SI->getOpcode() == Instruction::Shl)
2949 SrcByte = DestByte - ShiftBytes;
2950 else
2951 SrcByte = DestByte + ShiftBytes;
2952
2953 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2954 if (SrcByte != ByteValues.size()-DestByte-1)
2955 return true;
2956
2957 // If the destination byte value is already defined, the values are or'd
2958 // together, which isn't a bswap (unless it's an or of the same bits).
2959 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2960 return true;
2961 ByteValues[DestByte] = SI->getOperand(0);
2962 return false;
2963}
2964
2965/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2966/// If so, insert the new bswap intrinsic and return it.
2967Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2968 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2969 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2970 return 0;
2971
2972 /// ByteValues - For each byte of the result, we keep track of which value
2973 /// defines each byte.
2974 std::vector<Value*> ByteValues;
2975 ByteValues.resize(I.getType()->getPrimitiveSize());
2976
2977 // Try to find all the pieces corresponding to the bswap.
2978 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
2979 CollectBSwapParts(I.getOperand(1), ByteValues))
2980 return 0;
2981
2982 // Check to see if all of the bytes come from the same value.
2983 Value *V = ByteValues[0];
2984 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2985
2986 // Check to make sure that all of the bytes come from the same value.
2987 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2988 if (ByteValues[i] != V)
2989 return 0;
2990
2991 // If they do then *success* we can turn this into a bswap. Figure out what
2992 // bswap to make it into.
2993 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00002994 const char *FnName = 0;
Chris Lattnerafe91a52006-06-15 19:07:26 +00002995 if (I.getType() == Type::UShortTy)
2996 FnName = "llvm.bswap.i16";
2997 else if (I.getType() == Type::UIntTy)
2998 FnName = "llvm.bswap.i32";
2999 else if (I.getType() == Type::ULongTy)
3000 FnName = "llvm.bswap.i64";
3001 else
3002 assert(0 && "Unknown integer type!");
3003 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3004
3005 return new CallInst(F, V);
3006}
3007
3008
Chris Lattner7e708292002-06-25 16:13:24 +00003009Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003010 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003012
Chris Lattnere87597f2004-10-16 18:11:37 +00003013 if (isa<UndefValue>(Op1))
3014 return ReplaceInstUsesWith(I, // X | undef -> -1
3015 ConstantIntegral::getAllOnesValue(I.getType()));
3016
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003017 // or X, X = X
3018 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003019 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003020
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003021 // See if we can simplify any instructions used by the instruction whose sole
3022 // purpose is to compute bits we don't care about.
3023 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003024 if (!isa<PackedType>(I.getType()) &&
3025 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003026 KnownZero, KnownOne))
3027 return &I;
3028
Chris Lattner3f5b8772002-05-06 16:14:14 +00003029 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003030 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003031 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003032 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3033 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003034 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3035 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003036 InsertNewInstBefore(Or, I);
3037 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3038 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003039
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003040 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3041 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3042 std::string Op0Name = Op0->getName(); Op0->setName("");
3043 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3044 InsertNewInstBefore(Or, I);
3045 return BinaryOperator::createXor(Or,
3046 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003047 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003048
3049 // Try to fold constant and into select arguments.
3050 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003052 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003053 if (isa<PHINode>(Op0))
3054 if (Instruction *NV = FoldOpIntoPhi(I))
3055 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003056 }
3057
Chris Lattner4f637d42006-01-06 17:59:59 +00003058 Value *A = 0, *B = 0;
3059 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003060
3061 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3062 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3063 return ReplaceInstUsesWith(I, Op1);
3064 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3065 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3066 return ReplaceInstUsesWith(I, Op0);
3067
Chris Lattner6423d4c2006-07-10 20:25:24 +00003068 // (A | B) | C and A | (B | C) -> bswap if possible.
3069 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003070 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003071 match(Op1, m_Or(m_Value(), m_Value())) ||
3072 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3073 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003074 if (Instruction *BSwap = MatchBSwap(I))
3075 return BSwap;
3076 }
3077
Chris Lattner6e4c6492005-05-09 04:58:36 +00003078 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3079 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003080 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003081 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3082 Op0->setName("");
3083 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3084 }
3085
3086 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3087 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003088 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003089 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3090 Op0->setName("");
3091 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3092 }
3093
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003094 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003095 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003096 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3097
3098 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3099 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3100
3101
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003102 // If we have: ((V + N) & C1) | (V & C2)
3103 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3104 // replace with V+N.
3105 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003106 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003107 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3108 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3109 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003110 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003111 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003112 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003113 return ReplaceInstUsesWith(I, A);
3114 }
3115 // Or commutes, try both ways.
3116 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3117 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3118 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003119 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003120 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003121 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003122 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003123 }
3124 }
3125 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003126
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003127 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3128 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003129 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003130 ConstantIntegral::getAllOnesValue(I.getType()));
3131 } else {
3132 A = 0;
3133 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003134 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003135 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3136 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003137 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003138 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003139
Misha Brukmancb6267b2004-07-30 12:50:08 +00003140 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003141 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3142 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3143 I.getName()+".demorgan"), I);
3144 return BinaryOperator::createNot(And);
3145 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003146 }
Chris Lattnera2881962003-02-18 19:28:33 +00003147
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003148 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003149 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003150 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3151 return R;
3152
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003153 Value *LHSVal, *RHSVal;
3154 ConstantInt *LHSCst, *RHSCst;
3155 Instruction::BinaryOps LHSCC, RHSCC;
3156 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3157 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3158 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3159 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003160 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003161 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3162 // Ensure that the larger constant is on the RHS.
3163 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3164 SetCondInst *LHS = cast<SetCondInst>(Op0);
3165 if (cast<ConstantBool>(Cmp)->getValue()) {
3166 std::swap(LHS, RHS);
3167 std::swap(LHSCst, RHSCst);
3168 std::swap(LHSCC, RHSCC);
3169 }
3170
3171 // At this point, we know we have have two setcc instructions
3172 // comparing a value against two constants and or'ing the result
3173 // together. Because of the above check, we know that we only have
3174 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3175 // FoldSetCCLogical check above), that the two constants are not
3176 // equal.
3177 assert(LHSCst != RHSCst && "Compares not folded above?");
3178
3179 switch (LHSCC) {
3180 default: assert(0 && "Unknown integer condition code!");
3181 case Instruction::SetEQ:
3182 switch (RHSCC) {
3183 default: assert(0 && "Unknown integer condition code!");
3184 case Instruction::SetEQ:
3185 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3186 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3187 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3188 LHSVal->getName()+".off");
3189 InsertNewInstBefore(Add, I);
3190 const Type *UnsType = Add->getType()->getUnsignedVersion();
3191 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3192 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3193 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3194 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3195 }
3196 break; // (X == 13 | X == 15) -> no change
3197
Chris Lattner240d6f42005-04-19 06:04:18 +00003198 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3199 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003200 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3201 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3202 return ReplaceInstUsesWith(I, RHS);
3203 }
3204 break;
3205 case Instruction::SetNE:
3206 switch (RHSCC) {
3207 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003208 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3209 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3210 return ReplaceInstUsesWith(I, LHS);
3211 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00003212 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003213 return ReplaceInstUsesWith(I, ConstantBool::True);
3214 }
3215 break;
3216 case Instruction::SetLT:
3217 switch (RHSCC) {
3218 default: assert(0 && "Unknown integer condition code!");
3219 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3220 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00003221 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3222 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003223 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3224 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3225 return ReplaceInstUsesWith(I, RHS);
3226 }
3227 break;
3228 case Instruction::SetGT:
3229 switch (RHSCC) {
3230 default: assert(0 && "Unknown integer condition code!");
3231 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3232 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3233 return ReplaceInstUsesWith(I, LHS);
3234 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3235 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3236 return ReplaceInstUsesWith(I, ConstantBool::True);
3237 }
3238 }
3239 }
3240 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003241
3242 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3243 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003244 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003245 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003246 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003247 // Only do this if the casts both really cause code to be generated.
3248 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3249 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003250 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3251 Op1C->getOperand(0),
3252 I.getName());
3253 InsertNewInstBefore(NewOp, I);
3254 return new CastInst(NewOp, I.getType());
3255 }
3256 }
3257
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003258
Chris Lattner7e708292002-06-25 16:13:24 +00003259 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003260}
3261
Chris Lattnerc317d392004-02-16 01:20:27 +00003262// XorSelf - Implements: X ^ X --> 0
3263struct XorSelf {
3264 Value *RHS;
3265 XorSelf(Value *rhs) : RHS(rhs) {}
3266 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3267 Instruction *apply(BinaryOperator &Xor) const {
3268 return &Xor;
3269 }
3270};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003271
3272
Chris Lattner7e708292002-06-25 16:13:24 +00003273Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003274 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003275 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003276
Chris Lattnere87597f2004-10-16 18:11:37 +00003277 if (isa<UndefValue>(Op1))
3278 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3279
Chris Lattnerc317d392004-02-16 01:20:27 +00003280 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3281 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3282 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003283 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003284 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003285
3286 // See if we can simplify any instructions used by the instruction whose sole
3287 // purpose is to compute bits we don't care about.
3288 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003289 if (!isa<PackedType>(I.getType()) &&
3290 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003291 KnownZero, KnownOne))
3292 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003293
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003294 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003295 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00003296 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003297 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00003298 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00003299 return new SetCondInst(SCI->getInverseCondition(),
3300 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003301
Chris Lattnerd65460f2003-11-05 01:06:05 +00003302 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003303 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3304 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003305 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3306 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003307 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003308 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003309 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003310
3311 // ~(~X & Y) --> (X | ~Y)
3312 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3313 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3314 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3315 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003316 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003317 Op0I->getOperand(1)->getName()+".not");
3318 InsertNewInstBefore(NotY, I);
3319 return BinaryOperator::createOr(Op0NotVal, NotY);
3320 }
3321 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003322
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003323 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003324 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003325 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003326 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003327 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3328 return BinaryOperator::createSub(
3329 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003330 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003331 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003332 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003333 } else if (Op0I->getOpcode() == Instruction::Or) {
3334 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3335 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3336 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3337 // Anything in both C1 and C2 is known to be zero, remove it from
3338 // NewRHS.
3339 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3340 NewRHS = ConstantExpr::getAnd(NewRHS,
3341 ConstantExpr::getNot(CommonBits));
3342 WorkList.push_back(Op0I);
3343 I.setOperand(0, Op0I->getOperand(0));
3344 I.setOperand(1, NewRHS);
3345 return &I;
3346 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003347 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003348 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003349
3350 // Try to fold constant and into select arguments.
3351 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003352 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003353 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003354 if (isa<PHINode>(Op0))
3355 if (Instruction *NV = FoldOpIntoPhi(I))
3356 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003357 }
3358
Chris Lattner8d969642003-03-10 23:06:50 +00003359 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003360 if (X == Op1)
3361 return ReplaceInstUsesWith(I,
3362 ConstantIntegral::getAllOnesValue(I.getType()));
3363
Chris Lattner8d969642003-03-10 23:06:50 +00003364 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003365 if (X == Op0)
3366 return ReplaceInstUsesWith(I,
3367 ConstantIntegral::getAllOnesValue(I.getType()));
3368
Chris Lattner64daab52006-04-01 08:03:55 +00003369 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003370 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003371 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003372 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003373 I.swapOperands();
3374 std::swap(Op0, Op1);
3375 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003376 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003377 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003378 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003379 } else if (Op1I->getOpcode() == Instruction::Xor) {
3380 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3381 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3382 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3383 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003384 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3385 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3386 Op1I->swapOperands();
3387 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3388 I.swapOperands(); // Simplified below.
3389 std::swap(Op0, Op1);
3390 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003391 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003392
Chris Lattner64daab52006-04-01 08:03:55 +00003393 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003394 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003395 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003396 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003397 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003398 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3399 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003400 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003401 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003402 } else if (Op0I->getOpcode() == Instruction::Xor) {
3403 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3404 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3405 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3406 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003407 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3408 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3409 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003410 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3411 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003412 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3413 InsertNewInstBefore(N, I);
3414 return BinaryOperator::createAnd(N, Op1);
3415 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003416 }
3417
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003418 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3419 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3420 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3421 return R;
3422
Chris Lattner6fc205f2006-05-05 06:39:07 +00003423 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3424 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003425 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003426 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003427 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003428 // Only do this if the casts both really cause code to be generated.
3429 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3430 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003431 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3432 Op1C->getOperand(0),
3433 I.getName());
3434 InsertNewInstBefore(NewOp, I);
3435 return new CastInst(NewOp, I.getType());
3436 }
3437 }
3438
Chris Lattner7e708292002-06-25 16:13:24 +00003439 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003440}
3441
Chris Lattnera96879a2004-09-29 17:40:11 +00003442/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3443/// overflowed for this type.
3444static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3445 ConstantInt *In2) {
3446 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3447 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3448}
3449
3450static bool isPositive(ConstantInt *C) {
3451 return cast<ConstantSInt>(C)->getValue() >= 0;
3452}
3453
3454/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3455/// overflowed for this type.
3456static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3457 ConstantInt *In2) {
3458 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3459
3460 if (In1->getType()->isUnsigned())
3461 return cast<ConstantUInt>(Result)->getValue() <
3462 cast<ConstantUInt>(In1)->getValue();
3463 if (isPositive(In1) != isPositive(In2))
3464 return false;
3465 if (isPositive(In1))
3466 return cast<ConstantSInt>(Result)->getValue() <
3467 cast<ConstantSInt>(In1)->getValue();
3468 return cast<ConstantSInt>(Result)->getValue() >
3469 cast<ConstantSInt>(In1)->getValue();
3470}
3471
Chris Lattner574da9b2005-01-13 20:14:25 +00003472/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3473/// code necessary to compute the offset from the base pointer (without adding
3474/// in the base pointer). Return the result as a signed integer of intptr size.
3475static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3476 TargetData &TD = IC.getTargetData();
3477 gep_type_iterator GTI = gep_type_begin(GEP);
3478 const Type *UIntPtrTy = TD.getIntPtrType();
3479 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3480 Value *Result = Constant::getNullValue(SIntPtrTy);
3481
3482 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003483 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003484
Chris Lattner574da9b2005-01-13 20:14:25 +00003485 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3486 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003487 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00003488 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3489 SIntPtrTy);
3490 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3491 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003492 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003493 Scale = ConstantExpr::getMul(OpC, Scale);
3494 if (Constant *RC = dyn_cast<Constant>(Result))
3495 Result = ConstantExpr::getAdd(RC, Scale);
3496 else {
3497 // Emit an add instruction.
3498 Result = IC.InsertNewInstBefore(
3499 BinaryOperator::createAdd(Result, Scale,
3500 GEP->getName()+".offs"), I);
3501 }
3502 }
3503 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003504 // Convert to correct type.
3505 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3506 Op->getName()+".c"), I);
3507 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003508 // We'll let instcombine(mul) convert this to a shl if possible.
3509 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3510 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003511
3512 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003513 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003514 GEP->getName()+".offs"), I);
3515 }
3516 }
3517 return Result;
3518}
3519
3520/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3521/// else. At this point we know that the GEP is on the LHS of the comparison.
3522Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3523 Instruction::BinaryOps Cond,
3524 Instruction &I) {
3525 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003526
3527 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3528 if (isa<PointerType>(CI->getOperand(0)->getType()))
3529 RHS = CI->getOperand(0);
3530
Chris Lattner574da9b2005-01-13 20:14:25 +00003531 Value *PtrBase = GEPLHS->getOperand(0);
3532 if (PtrBase == RHS) {
3533 // As an optimization, we don't actually have to compute the actual value of
3534 // OFFSET if this is a seteq or setne comparison, just return whether each
3535 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003536 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3537 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003538 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3539 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003540 bool EmitIt = true;
3541 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3542 if (isa<UndefValue>(C)) // undef index -> undef.
3543 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3544 if (C->isNullValue())
3545 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003546 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3547 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003548 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003549 return ReplaceInstUsesWith(I, // No comparison is needed here.
3550 ConstantBool::get(Cond == Instruction::SetNE));
3551 }
3552
3553 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003554 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003555 new SetCondInst(Cond, GEPLHS->getOperand(i),
3556 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3557 if (InVal == 0)
3558 InVal = Comp;
3559 else {
3560 InVal = InsertNewInstBefore(InVal, I);
3561 InsertNewInstBefore(Comp, I);
3562 if (Cond == Instruction::SetNE) // True if any are unequal
3563 InVal = BinaryOperator::createOr(InVal, Comp);
3564 else // True if all are equal
3565 InVal = BinaryOperator::createAnd(InVal, Comp);
3566 }
3567 }
3568 }
3569
3570 if (InVal)
3571 return InVal;
3572 else
3573 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3574 ConstantBool::get(Cond == Instruction::SetEQ));
3575 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003576
3577 // Only lower this if the setcc is the only user of the GEP or if we expect
3578 // the result to fold to a constant!
3579 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3580 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3581 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3582 return new SetCondInst(Cond, Offset,
3583 Constant::getNullValue(Offset->getType()));
3584 }
3585 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003586 // If the base pointers are different, but the indices are the same, just
3587 // compare the base pointer.
3588 if (PtrBase != GEPRHS->getOperand(0)) {
3589 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003590 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003591 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003592 if (IndicesTheSame)
3593 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3594 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3595 IndicesTheSame = false;
3596 break;
3597 }
3598
3599 // If all indices are the same, just compare the base pointers.
3600 if (IndicesTheSame)
3601 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3602 GEPRHS->getOperand(0));
3603
3604 // Otherwise, the base pointers are different and the indices are
3605 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003606 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003607 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003608
Chris Lattnere9d782b2005-01-13 22:25:21 +00003609 // If one of the GEPs has all zero indices, recurse.
3610 bool AllZeros = true;
3611 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3612 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3613 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3614 AllZeros = false;
3615 break;
3616 }
3617 if (AllZeros)
3618 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3619 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003620
3621 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003622 AllZeros = true;
3623 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3624 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3625 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3626 AllZeros = false;
3627 break;
3628 }
3629 if (AllZeros)
3630 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3631
Chris Lattner4401c9c2005-01-14 00:20:05 +00003632 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3633 // If the GEPs only differ by one index, compare it.
3634 unsigned NumDifferences = 0; // Keep track of # differences.
3635 unsigned DiffOperand = 0; // The operand that differs.
3636 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3637 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00003638 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3639 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003640 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00003641 NumDifferences = 2;
3642 break;
3643 } else {
3644 if (NumDifferences++) break;
3645 DiffOperand = i;
3646 }
3647 }
3648
3649 if (NumDifferences == 0) // SAME GEP?
3650 return ReplaceInstUsesWith(I, // No comparison is needed here.
3651 ConstantBool::get(Cond == Instruction::SetEQ));
3652 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003653 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3654 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00003655
3656 // Convert the operands to signed values to make sure to perform a
3657 // signed comparison.
3658 const Type *NewTy = LHSV->getType()->getSignedVersion();
3659 if (LHSV->getType() != NewTy)
3660 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3661 LHSV->getName()), I);
3662 if (RHSV->getType() != NewTy)
3663 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3664 RHSV->getName()), I);
3665 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003666 }
3667 }
3668
Chris Lattner574da9b2005-01-13 20:14:25 +00003669 // Only lower this if the setcc is the only user of the GEP or if we expect
3670 // the result to fold to a constant!
3671 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3672 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3673 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3674 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3675 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3676 return new SetCondInst(Cond, L, R);
3677 }
3678 }
3679 return 0;
3680}
3681
3682
Chris Lattner484d3cf2005-04-24 06:59:08 +00003683Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003684 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00003685 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3686 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00003687
3688 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00003689 if (Op0 == Op1)
3690 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00003691
Chris Lattnere87597f2004-10-16 18:11:37 +00003692 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3693 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3694
Chris Lattner711b3402004-11-14 07:33:16 +00003695 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3696 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00003697 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3698 isa<ConstantPointerNull>(Op0)) &&
3699 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00003700 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00003701 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3702
3703 // setcc's with boolean values can always be turned into bitwise operations
3704 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00003705 switch (I.getOpcode()) {
3706 default: assert(0 && "Invalid setcc instruction!");
3707 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00003708 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00003709 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00003710 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00003711 }
Chris Lattner5dbef222004-08-11 00:50:51 +00003712 case Instruction::SetNE:
3713 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00003714
Chris Lattner5dbef222004-08-11 00:50:51 +00003715 case Instruction::SetGT:
3716 std::swap(Op0, Op1); // Change setgt -> setlt
3717 // FALL THROUGH
3718 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3719 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3720 InsertNewInstBefore(Not, I);
3721 return BinaryOperator::createAnd(Not, Op1);
3722 }
3723 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00003724 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00003725 // FALL THROUGH
3726 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3727 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3728 InsertNewInstBefore(Not, I);
3729 return BinaryOperator::createOr(Not, Op1);
3730 }
3731 }
Chris Lattner8b170942002-08-09 23:47:40 +00003732 }
3733
Chris Lattner2be51ae2004-06-09 04:24:29 +00003734 // See if we are doing a comparison between a constant and an instruction that
3735 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00003736 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003737 // Check to see if we are comparing against the minimum or maximum value...
3738 if (CI->isMinValue()) {
3739 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3740 return ReplaceInstUsesWith(I, ConstantBool::False);
3741 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3742 return ReplaceInstUsesWith(I, ConstantBool::True);
3743 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3744 return BinaryOperator::createSetEQ(Op0, Op1);
3745 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3746 return BinaryOperator::createSetNE(Op0, Op1);
3747
3748 } else if (CI->isMaxValue()) {
3749 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3750 return ReplaceInstUsesWith(I, ConstantBool::False);
3751 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3752 return ReplaceInstUsesWith(I, ConstantBool::True);
3753 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3754 return BinaryOperator::createSetEQ(Op0, Op1);
3755 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3756 return BinaryOperator::createSetNE(Op0, Op1);
3757
3758 // Comparing against a value really close to min or max?
3759 } else if (isMinValuePlusOne(CI)) {
3760 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3761 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3762 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3763 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3764
3765 } else if (isMaxValueMinusOne(CI)) {
3766 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3767 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3768 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3769 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3770 }
3771
3772 // If we still have a setle or setge instruction, turn it into the
3773 // appropriate setlt or setgt instruction. Since the border cases have
3774 // already been handled above, this requires little checking.
3775 //
3776 if (I.getOpcode() == Instruction::SetLE)
3777 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3778 if (I.getOpcode() == Instruction::SetGE)
3779 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3780
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003781
3782 // See if we can fold the comparison based on bits known to be zero or one
3783 // in the input.
3784 uint64_t KnownZero, KnownOne;
3785 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3786 KnownZero, KnownOne, 0))
3787 return &I;
3788
3789 // Given the known and unknown bits, compute a range that the LHS could be
3790 // in.
3791 if (KnownOne | KnownZero) {
3792 if (Ty->isUnsigned()) { // Unsigned comparison.
3793 uint64_t Min, Max;
3794 uint64_t RHSVal = CI->getZExtValue();
3795 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3796 Min, Max);
3797 switch (I.getOpcode()) { // LE/GE have been folded already.
3798 default: assert(0 && "Unknown setcc opcode!");
3799 case Instruction::SetEQ:
3800 if (Max < RHSVal || Min > RHSVal)
3801 return ReplaceInstUsesWith(I, ConstantBool::False);
3802 break;
3803 case Instruction::SetNE:
3804 if (Max < RHSVal || Min > RHSVal)
3805 return ReplaceInstUsesWith(I, ConstantBool::True);
3806 break;
3807 case Instruction::SetLT:
3808 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3809 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3810 break;
3811 case Instruction::SetGT:
3812 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3813 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3814 break;
3815 }
3816 } else { // Signed comparison.
3817 int64_t Min, Max;
3818 int64_t RHSVal = CI->getSExtValue();
3819 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3820 Min, Max);
3821 switch (I.getOpcode()) { // LE/GE have been folded already.
3822 default: assert(0 && "Unknown setcc opcode!");
3823 case Instruction::SetEQ:
3824 if (Max < RHSVal || Min > RHSVal)
3825 return ReplaceInstUsesWith(I, ConstantBool::False);
3826 break;
3827 case Instruction::SetNE:
3828 if (Max < RHSVal || Min > RHSVal)
3829 return ReplaceInstUsesWith(I, ConstantBool::True);
3830 break;
3831 case Instruction::SetLT:
3832 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3833 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3834 break;
3835 case Instruction::SetGT:
3836 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3837 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3838 break;
3839 }
3840 }
3841 }
3842
3843
Chris Lattner3c6a0d42004-05-25 06:32:08 +00003844 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00003845 switch (LHSI->getOpcode()) {
3846 case Instruction::And:
3847 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3848 LHSI->getOperand(0)->hasOneUse()) {
3849 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3850 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3851 // happens a LOT in code produced by the C front-end, for bitfield
3852 // access.
3853 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003854 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3855
3856 // Check to see if there is a noop-cast between the shift and the and.
3857 if (!Shift) {
3858 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3859 if (CI->getOperand(0)->getType()->isIntegral() &&
3860 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3861 CI->getType()->getPrimitiveSizeInBits())
3862 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3863 }
3864
Chris Lattner648e3bc2004-09-23 21:52:49 +00003865 ConstantUInt *ShAmt;
3866 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003867 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3868 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00003869
Chris Lattner648e3bc2004-09-23 21:52:49 +00003870 // We can fold this as long as we can't shift unknown bits
3871 // into the mask. This can only happen with signed shift
3872 // rights, as they sign-extend.
3873 if (ShAmt) {
3874 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003875 Ty->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00003876 if (!CanFold) {
3877 // To test for the bad case of the signed shr, see if any
3878 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00003879 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3880 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3881
3882 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00003883 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003884 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3885 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00003886 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3887 CanFold = true;
3888 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003889
Chris Lattner648e3bc2004-09-23 21:52:49 +00003890 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00003891 Constant *NewCst;
3892 if (Shift->getOpcode() == Instruction::Shl)
3893 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3894 else
3895 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003896
Chris Lattner648e3bc2004-09-23 21:52:49 +00003897 // Check to see if we are shifting out any of the bits being
3898 // compared.
3899 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3900 // If we shifted bits out, the fold is not going to work out.
3901 // As a special case, check to see if this means that the
3902 // result is always true or false now.
3903 if (I.getOpcode() == Instruction::SetEQ)
3904 return ReplaceInstUsesWith(I, ConstantBool::False);
3905 if (I.getOpcode() == Instruction::SetNE)
3906 return ReplaceInstUsesWith(I, ConstantBool::True);
3907 } else {
3908 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00003909 Constant *NewAndCST;
3910 if (Shift->getOpcode() == Instruction::Shl)
3911 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3912 else
3913 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3914 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003915 if (AndTy == Ty)
3916 LHSI->setOperand(0, Shift->getOperand(0));
3917 else {
3918 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3919 *Shift);
3920 LHSI->setOperand(0, NewCast);
3921 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003922 WorkList.push_back(Shift); // Shift is dead.
3923 AddUsesToWorkList(I);
3924 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00003925 }
3926 }
Chris Lattner457dd822004-06-09 07:59:58 +00003927 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003928 }
3929 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003930
Chris Lattner18d19ca2004-09-28 18:22:15 +00003931 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3932 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3933 switch (I.getOpcode()) {
3934 default: break;
3935 case Instruction::SetEQ:
3936 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003937 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3938
3939 // Check that the shift amount is in range. If not, don't perform
3940 // undefined shifts. When the shift is visited it will be
3941 // simplified.
3942 if (ShAmt->getValue() >= TypeBits)
3943 break;
3944
Chris Lattner18d19ca2004-09-28 18:22:15 +00003945 // If we are comparing against bits always shifted out, the
3946 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003947 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003948 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3949 if (Comp != CI) {// Comparing against a bit that we know is zero.
3950 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3951 Constant *Cst = ConstantBool::get(IsSetNE);
3952 return ReplaceInstUsesWith(I, Cst);
3953 }
3954
3955 if (LHSI->hasOneUse()) {
3956 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003957 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003958 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3959
3960 Constant *Mask;
3961 if (CI->getType()->isUnsigned()) {
3962 Mask = ConstantUInt::get(CI->getType(), Val);
3963 } else if (ShAmtVal != 0) {
3964 Mask = ConstantSInt::get(CI->getType(), Val);
3965 } else {
3966 Mask = ConstantInt::getAllOnesValue(CI->getType());
3967 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003968
Chris Lattner18d19ca2004-09-28 18:22:15 +00003969 Instruction *AndI =
3970 BinaryOperator::createAnd(LHSI->getOperand(0),
3971 Mask, LHSI->getName()+".mask");
3972 Value *And = InsertNewInstBefore(AndI, I);
3973 return new SetCondInst(I.getOpcode(), And,
3974 ConstantExpr::getUShr(CI, ShAmt));
3975 }
3976 }
3977 }
3978 }
3979 break;
3980
Chris Lattner83c4ec02004-09-27 19:29:18 +00003981 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003982 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003983 switch (I.getOpcode()) {
3984 default: break;
3985 case Instruction::SetEQ:
3986 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003987
3988 // Check that the shift amount is in range. If not, don't perform
3989 // undefined shifts. When the shift is visited it will be
3990 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003991 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003992 if (ShAmt->getValue() >= TypeBits)
3993 break;
3994
Chris Lattnerf63f6472004-09-27 16:18:50 +00003995 // If we are comparing against bits always shifted out, the
3996 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003997 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003998 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003999
Chris Lattnerf63f6472004-09-27 16:18:50 +00004000 if (Comp != CI) {// Comparing against a bit that we know is zero.
4001 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4002 Constant *Cst = ConstantBool::get(IsSetNE);
4003 return ReplaceInstUsesWith(I, Cst);
4004 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004005
Chris Lattnerf63f6472004-09-27 16:18:50 +00004006 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00004007 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004008
Chris Lattnerf63f6472004-09-27 16:18:50 +00004009 // Otherwise strength reduce the shift into an and.
4010 uint64_t Val = ~0ULL; // All ones.
4011 Val <<= ShAmtVal; // Shift over to the right spot.
4012
4013 Constant *Mask;
4014 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00004015 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004016 Mask = ConstantUInt::get(CI->getType(), Val);
4017 } else {
4018 Mask = ConstantSInt::get(CI->getType(), Val);
4019 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004020
Chris Lattnerf63f6472004-09-27 16:18:50 +00004021 Instruction *AndI =
4022 BinaryOperator::createAnd(LHSI->getOperand(0),
4023 Mask, LHSI->getName()+".mask");
4024 Value *And = InsertNewInstBefore(AndI, I);
4025 return new SetCondInst(I.getOpcode(), And,
4026 ConstantExpr::getShl(CI, ShAmt));
4027 }
4028 break;
4029 }
4030 }
4031 }
4032 break;
Chris Lattner0c967662004-09-24 15:21:34 +00004033
Chris Lattnera96879a2004-09-29 17:40:11 +00004034 case Instruction::Div:
4035 // Fold: (div X, C1) op C2 -> range check
4036 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4037 // Fold this div into the comparison, producing a range check.
4038 // Determine, based on the divide type, what the range is being
4039 // checked. If there is an overflow on the low or high side, remember
4040 // it, otherwise compute the range [low, hi) bounding the new value.
4041 bool LoOverflow = false, HiOverflow = 0;
4042 ConstantInt *LoBound = 0, *HiBound = 0;
4043
4044 ConstantInt *Prod;
4045 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4046
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004047 Instruction::BinaryOps Opcode = I.getOpcode();
4048
Chris Lattnera96879a2004-09-29 17:40:11 +00004049 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4050 } else if (LHSI->getType()->isUnsigned()) { // udiv
4051 LoBound = Prod;
4052 LoOverflow = ProdOV;
4053 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4054 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4055 if (CI->isNullValue()) { // (X / pos) op 0
4056 // Can't overflow.
4057 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4058 HiBound = DivRHS;
4059 } else if (isPositive(CI)) { // (X / pos) op pos
4060 LoBound = Prod;
4061 LoOverflow = ProdOV;
4062 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4063 } else { // (X / pos) op neg
4064 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4065 LoOverflow = AddWithOverflow(LoBound, Prod,
4066 cast<ConstantInt>(DivRHSH));
4067 HiBound = Prod;
4068 HiOverflow = ProdOV;
4069 }
4070 } else { // Divisor is < 0.
4071 if (CI->isNullValue()) { // (X / neg) op 0
4072 LoBound = AddOne(DivRHS);
4073 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00004074 if (HiBound == DivRHS)
4075 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00004076 } else if (isPositive(CI)) { // (X / neg) op pos
4077 HiOverflow = LoOverflow = ProdOV;
4078 if (!LoOverflow)
4079 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4080 HiBound = AddOne(Prod);
4081 } else { // (X / neg) op neg
4082 LoBound = Prod;
4083 LoOverflow = HiOverflow = ProdOV;
4084 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4085 }
Chris Lattner340a05f2004-10-08 19:15:44 +00004086
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004087 // Dividing by a negate swaps the condition.
4088 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00004089 }
4090
4091 if (LoBound) {
4092 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004093 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004094 default: assert(0 && "Unhandled setcc opcode!");
4095 case Instruction::SetEQ:
4096 if (LoOverflow && HiOverflow)
4097 return ReplaceInstUsesWith(I, ConstantBool::False);
4098 else if (HiOverflow)
4099 return new SetCondInst(Instruction::SetGE, X, LoBound);
4100 else if (LoOverflow)
4101 return new SetCondInst(Instruction::SetLT, X, HiBound);
4102 else
4103 return InsertRangeTest(X, LoBound, HiBound, true, I);
4104 case Instruction::SetNE:
4105 if (LoOverflow && HiOverflow)
4106 return ReplaceInstUsesWith(I, ConstantBool::True);
4107 else if (HiOverflow)
4108 return new SetCondInst(Instruction::SetLT, X, LoBound);
4109 else if (LoOverflow)
4110 return new SetCondInst(Instruction::SetGE, X, HiBound);
4111 else
4112 return InsertRangeTest(X, LoBound, HiBound, false, I);
4113 case Instruction::SetLT:
4114 if (LoOverflow)
4115 return ReplaceInstUsesWith(I, ConstantBool::False);
4116 return new SetCondInst(Instruction::SetLT, X, LoBound);
4117 case Instruction::SetGT:
4118 if (HiOverflow)
4119 return ReplaceInstUsesWith(I, ConstantBool::False);
4120 return new SetCondInst(Instruction::SetGE, X, HiBound);
4121 }
4122 }
4123 }
4124 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00004125 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004126
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004127 // Simplify seteq and setne instructions...
4128 if (I.getOpcode() == Instruction::SetEQ ||
4129 I.getOpcode() == Instruction::SetNE) {
4130 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4131
Chris Lattner00b1a7e2003-07-23 17:26:36 +00004132 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004133 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00004134 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4135 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00004136 case Instruction::Rem:
4137 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4138 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4139 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004140 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4141 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4142 if (isPowerOf2_64(V)) {
4143 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00004144 const Type *UTy = BO->getType()->getUnsignedVersion();
4145 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4146 UTy, "tmp"), I);
4147 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4148 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4149 RHSCst, BO->getName()), I);
4150 return BinaryOperator::create(I.getOpcode(), NewRem,
4151 Constant::getNullValue(UTy));
4152 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004153 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004154 break;
Chris Lattner3571b722004-07-06 07:38:18 +00004155
Chris Lattner934754b2003-08-13 05:33:12 +00004156 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00004157 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4158 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00004159 if (BO->hasOneUse())
4160 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4161 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00004162 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004163 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4164 // efficiently invertible, or if the add has just this one use.
4165 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004166
Chris Lattner934754b2003-08-13 05:33:12 +00004167 if (Value *NegVal = dyn_castNegVal(BOp1))
4168 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4169 else if (Value *NegVal = dyn_castNegVal(BOp0))
4170 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00004171 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004172 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4173 BO->setName("");
4174 InsertNewInstBefore(Neg, I);
4175 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4176 }
4177 }
4178 break;
4179 case Instruction::Xor:
4180 // For the xor case, we can xor two constants together, eliminating
4181 // the explicit xor.
4182 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4183 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00004184 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00004185
4186 // FALLTHROUGH
4187 case Instruction::Sub:
4188 // Replace (([sub|xor] A, B) != 0) with (A != B)
4189 if (CI->isNullValue())
4190 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4191 BO->getOperand(1));
4192 break;
4193
4194 case Instruction::Or:
4195 // If bits are being or'd in that are not present in the constant we
4196 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00004197 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00004198 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00004199 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004200 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004201 }
Chris Lattner934754b2003-08-13 05:33:12 +00004202 break;
4203
4204 case Instruction::And:
4205 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004206 // If bits are being compared against that are and'd out, then the
4207 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00004208 if (!ConstantExpr::getAnd(CI,
4209 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004210 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00004211
Chris Lattner457dd822004-06-09 07:59:58 +00004212 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00004213 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00004214 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4215 Instruction::SetNE, Op0,
4216 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00004217
Chris Lattner934754b2003-08-13 05:33:12 +00004218 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4219 // to be a signed value as appropriate.
4220 if (isSignBit(BOC)) {
4221 Value *X = BO->getOperand(0);
4222 // If 'X' is not signed, insert a cast now...
4223 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00004224 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00004225 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00004226 }
4227 return new SetCondInst(isSetNE ? Instruction::SetLT :
4228 Instruction::SetGE, X,
4229 Constant::getNullValue(X->getType()));
4230 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004231
Chris Lattner83c4ec02004-09-27 19:29:18 +00004232 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004233 if (CI->isNullValue() && isHighOnes(BOC)) {
4234 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004235 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004236
4237 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00004238 if (NegX->getType()->isSigned()) {
4239 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4240 X = InsertCastBefore(X, DestTy, I);
4241 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004242 }
4243
4244 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00004245 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004246 }
4247
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004248 }
Chris Lattner934754b2003-08-13 05:33:12 +00004249 default: break;
4250 }
4251 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004252 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00004253 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004254 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4255 Value *CastOp = Cast->getOperand(0);
4256 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004257 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004258 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004259 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004260 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004261 "Source and destination signednesses should differ!");
4262 if (Cast->getType()->isSigned()) {
4263 // If this is a signed comparison, check for comparisons in the
4264 // vicinity of zero.
4265 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4266 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00004267 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00004268 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004269 else if (I.getOpcode() == Instruction::SetGT &&
4270 cast<ConstantSInt>(CI)->getValue() == -1)
4271 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00004272 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00004273 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004274 } else {
4275 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4276 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004277 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004278 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00004279 return BinaryOperator::createSetGT(CastOp,
4280 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004281 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004282 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004283 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00004284 return BinaryOperator::createSetLT(CastOp,
4285 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004286 }
4287 }
4288 }
Chris Lattner40f5d702003-06-04 05:10:11 +00004289 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004290 }
4291
Chris Lattner6970b662005-04-23 15:31:55 +00004292 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4293 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4294 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4295 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004296 case Instruction::GetElementPtr:
4297 if (RHSC->isNullValue()) {
4298 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4299 bool isAllZeros = true;
4300 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4301 if (!isa<Constant>(LHSI->getOperand(i)) ||
4302 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4303 isAllZeros = false;
4304 break;
4305 }
4306 if (isAllZeros)
4307 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4308 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4309 }
4310 break;
4311
Chris Lattner6970b662005-04-23 15:31:55 +00004312 case Instruction::PHI:
4313 if (Instruction *NV = FoldOpIntoPhi(I))
4314 return NV;
4315 break;
4316 case Instruction::Select:
4317 // If either operand of the select is a constant, we can fold the
4318 // comparison into the select arms, which will cause one to be
4319 // constant folded and the select turned into a bitwise or.
4320 Value *Op1 = 0, *Op2 = 0;
4321 if (LHSI->hasOneUse()) {
4322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4323 // Fold the known value into the constant operand.
4324 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4325 // Insert a new SetCC of the other select operand.
4326 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4327 LHSI->getOperand(2), RHSC,
4328 I.getName()), I);
4329 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4330 // Fold the known value into the constant operand.
4331 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4332 // Insert a new SetCC of the other select operand.
4333 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4334 LHSI->getOperand(1), RHSC,
4335 I.getName()), I);
4336 }
4337 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004338
Chris Lattner6970b662005-04-23 15:31:55 +00004339 if (Op1)
4340 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4341 break;
4342 }
4343 }
4344
Chris Lattner574da9b2005-01-13 20:14:25 +00004345 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4346 if (User *GEP = dyn_castGetElementPtr(Op0))
4347 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4348 return NI;
4349 if (User *GEP = dyn_castGetElementPtr(Op1))
4350 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4351 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4352 return NI;
4353
Chris Lattnerde90b762003-11-03 04:25:02 +00004354 // Test to see if the operands of the setcc are casted versions of other
4355 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00004356 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4357 Value *CastOp0 = CI->getOperand(0);
4358 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00004359 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00004360 (I.getOpcode() == Instruction::SetEQ ||
4361 I.getOpcode() == Instruction::SetNE)) {
4362 // We keep moving the cast from the left operand over to the right
4363 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00004364 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00004365
Chris Lattnerde90b762003-11-03 04:25:02 +00004366 // If operand #1 is a cast instruction, see if we can eliminate it as
4367 // well.
Chris Lattner68708052003-11-03 05:17:03 +00004368 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4369 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00004370 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00004371 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004372
Chris Lattnerde90b762003-11-03 04:25:02 +00004373 // If Op1 is a constant, we can fold the cast into the constant.
4374 if (Op1->getType() != Op0->getType())
4375 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4376 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4377 } else {
4378 // Otherwise, cast the RHS right before the setcc
4379 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4380 InsertNewInstBefore(cast<Instruction>(Op1), I);
4381 }
4382 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4383 }
4384
Chris Lattner68708052003-11-03 05:17:03 +00004385 // Handle the special case of: setcc (cast bool to X), <cst>
4386 // This comes up when you have code like
4387 // int X = A < B;
4388 // if (X) ...
4389 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00004390 // with a constant or another cast from the same type.
4391 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4392 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4393 return R;
Chris Lattner68708052003-11-03 05:17:03 +00004394 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004395
4396 if (I.getOpcode() == Instruction::SetNE ||
4397 I.getOpcode() == Instruction::SetEQ) {
4398 Value *A, *B;
4399 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4400 (A == Op1 || B == Op1)) {
4401 // (A^B) == A -> B == 0
4402 Value *OtherVal = A == Op1 ? B : A;
4403 return BinaryOperator::create(I.getOpcode(), OtherVal,
4404 Constant::getNullValue(A->getType()));
4405 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4406 (A == Op0 || B == Op0)) {
4407 // A == (A^B) -> B == 0
4408 Value *OtherVal = A == Op0 ? B : A;
4409 return BinaryOperator::create(I.getOpcode(), OtherVal,
4410 Constant::getNullValue(A->getType()));
4411 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4412 // (A-B) == A -> B == 0
4413 return BinaryOperator::create(I.getOpcode(), B,
4414 Constant::getNullValue(B->getType()));
4415 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4416 // A == (A-B) -> B == 0
4417 return BinaryOperator::create(I.getOpcode(), B,
4418 Constant::getNullValue(B->getType()));
4419 }
4420 }
Chris Lattner7e708292002-06-25 16:13:24 +00004421 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004422}
4423
Chris Lattner484d3cf2005-04-24 06:59:08 +00004424// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4425// We only handle extending casts so far.
4426//
4427Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4428 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4429 const Type *SrcTy = LHSCIOp->getType();
4430 const Type *DestTy = SCI.getOperand(0)->getType();
4431 Value *RHSCIOp;
4432
4433 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004434 return 0;
4435
Chris Lattner484d3cf2005-04-24 06:59:08 +00004436 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4437 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4438 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4439
4440 // Is this a sign or zero extension?
4441 bool isSignSrc = SrcTy->isSigned();
4442 bool isSignDest = DestTy->isSigned();
4443
4444 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4445 // Not an extension from the same type?
4446 RHSCIOp = CI->getOperand(0);
4447 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4448 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4449 // Compute the constant that would happen if we truncated to SrcTy then
4450 // reextended to DestTy.
4451 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4452
4453 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4454 RHSCIOp = Res;
4455 } else {
4456 // If the value cannot be represented in the shorter type, we cannot emit
4457 // a simple comparison.
4458 if (SCI.getOpcode() == Instruction::SetEQ)
4459 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4460 if (SCI.getOpcode() == Instruction::SetNE)
4461 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4462
Chris Lattner484d3cf2005-04-24 06:59:08 +00004463 // Evaluate the comparison for LT.
4464 Value *Result;
4465 if (DestTy->isSigned()) {
4466 // We're performing a signed comparison.
4467 if (isSignSrc) {
4468 // Signed extend and signed comparison.
4469 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4470 Result = ConstantBool::False;
4471 else
4472 Result = ConstantBool::True; // X < (large) --> true
4473 } else {
4474 // Unsigned extend and signed comparison.
4475 if (cast<ConstantSInt>(CI)->getValue() < 0)
4476 Result = ConstantBool::False;
4477 else
4478 Result = ConstantBool::True;
4479 }
4480 } else {
4481 // We're performing an unsigned comparison.
4482 if (!isSignSrc) {
4483 // Unsigned extend & compare -> always true.
4484 Result = ConstantBool::True;
4485 } else {
4486 // We're performing an unsigned comp with a sign extended value.
4487 // This is true if the input is >= 0. [aka >s -1]
4488 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4489 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4490 NegOne, SCI.getName()), SCI);
4491 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004492 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004493
Jeff Cohen00b168892005-07-27 06:12:32 +00004494 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004495 if (SCI.getOpcode() == Instruction::SetLT) {
4496 return ReplaceInstUsesWith(SCI, Result);
4497 } else {
4498 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4499 if (Constant *CI = dyn_cast<Constant>(Result))
4500 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4501 else
4502 return BinaryOperator::createNot(Result);
4503 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004504 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004505 } else {
4506 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004507 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004508
Chris Lattner8d7089e2005-06-16 03:00:08 +00004509 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004510 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4511}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004512
Chris Lattnerea340052003-03-10 19:16:08 +00004513Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004514 assert(I.getOperand(1)->getType() == Type::UByteTy);
4515 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004516 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004517
4518 // shl X, 0 == X and shr X, 0 == X
4519 // shl 0, X == 0 and shr 0, X == 0
4520 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004521 Op0 == Constant::getNullValue(Op0->getType()))
4522 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004523
Chris Lattnere87597f2004-10-16 18:11:37 +00004524 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4525 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004526 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004527 else // undef << X -> 0 AND undef >>u X -> 0
4528 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4529 }
4530 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00004531 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00004532 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4533 else
4534 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4535 }
4536
Chris Lattnerdf17af12003-08-12 21:53:41 +00004537 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4538 if (!isLeftShift)
4539 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4540 if (CSI->isAllOnesValue())
4541 return ReplaceInstUsesWith(I, CSI);
4542
Chris Lattner2eefe512004-04-09 19:05:30 +00004543 // Try to fold constant and into select arguments.
4544 if (isa<Constant>(Op0))
4545 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004546 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004547 return R;
4548
Chris Lattner120347e2005-05-08 17:34:56 +00004549 // See if we can turn a signed shr into an unsigned shr.
4550 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00004551 if (MaskedValueIsZero(Op0,
4552 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00004553 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4554 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4555 I.getName()), I);
4556 return new CastInst(V, I.getType());
4557 }
4558 }
Jeff Cohen00b168892005-07-27 06:12:32 +00004559
Chris Lattner4d5542c2006-01-06 07:12:35 +00004560 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4561 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4562 return Res;
4563 return 0;
4564}
4565
4566Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4567 ShiftInst &I) {
4568 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00004569 bool isSignedShift = Op0->getType()->isSigned();
4570 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004571
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004572 // See if we can simplify any instructions used by the instruction whose sole
4573 // purpose is to compute bits we don't care about.
4574 uint64_t KnownZero, KnownOne;
4575 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4576 KnownZero, KnownOne))
4577 return &I;
4578
Chris Lattner4d5542c2006-01-06 07:12:35 +00004579 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4580 // of a signed value.
4581 //
4582 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4583 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00004584 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00004585 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4586 else {
4587 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4588 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004589 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004590 }
4591
4592 // ((X*C1) << C2) == (X * (C1 << C2))
4593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4594 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4595 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4596 return BinaryOperator::createMul(BO->getOperand(0),
4597 ConstantExpr::getShl(BOOp, Op1));
4598
4599 // Try to fold constant and into select arguments.
4600 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4601 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4602 return R;
4603 if (isa<PHINode>(Op0))
4604 if (Instruction *NV = FoldOpIntoPhi(I))
4605 return NV;
4606
4607 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004608 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4609 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4610 Value *V1, *V2;
4611 ConstantInt *CC;
4612 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004613 default: break;
4614 case Instruction::Add:
4615 case Instruction::And:
4616 case Instruction::Or:
4617 case Instruction::Xor:
4618 // These operators commute.
4619 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004620 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4621 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004622 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004623 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004624 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004625 Op0BO->getName());
4626 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004627 Instruction *X =
4628 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4629 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004630 InsertNewInstBefore(X, I); // (X + (Y << C))
4631 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004632 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004633 return BinaryOperator::createAnd(X, C2);
4634 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004635
Chris Lattner150f12a2005-09-18 06:30:59 +00004636 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4637 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4638 match(Op0BO->getOperand(1),
4639 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004640 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004641 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004642 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004643 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004644 Op0BO->getName());
4645 InsertNewInstBefore(YS, I); // (Y << C)
4646 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004647 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004648 V1->getName()+".mask");
4649 InsertNewInstBefore(XM, I); // X & (CC << C)
4650
4651 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4652 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004653
Chris Lattner150f12a2005-09-18 06:30:59 +00004654 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00004655 case Instruction::Sub:
4656 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004657 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4658 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004659 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004660 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004661 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004662 Op0BO->getName());
4663 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004664 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00004665 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004666 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004667 InsertNewInstBefore(X, I); // (X + (Y << C))
4668 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004669 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004670 return BinaryOperator::createAnd(X, C2);
4671 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004672
Chris Lattner13d4ab42006-05-31 21:14:00 +00004673 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004674 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4675 match(Op0BO->getOperand(0),
4676 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004677 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004678 cast<BinaryOperator>(Op0BO->getOperand(0))
4679 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004680 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004681 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004682 Op0BO->getName());
4683 InsertNewInstBefore(YS, I); // (Y << C)
4684 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004685 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004686 V1->getName()+".mask");
4687 InsertNewInstBefore(XM, I); // X & (CC << C)
4688
Chris Lattner13d4ab42006-05-31 21:14:00 +00004689 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00004690 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004691
Chris Lattner11021cb2005-09-18 05:12:10 +00004692 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004693 }
4694
4695
4696 // If the operand is an bitwise operator with a constant RHS, and the
4697 // shift is the only use, we can pull it out of the shift.
4698 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4699 bool isValid = true; // Valid only for And, Or, Xor
4700 bool highBitSet = false; // Transform if high bit of constant set?
4701
4702 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004703 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004704 case Instruction::Add:
4705 isValid = isLeftShift;
4706 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004707 case Instruction::Or:
4708 case Instruction::Xor:
4709 highBitSet = false;
4710 break;
4711 case Instruction::And:
4712 highBitSet = true;
4713 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004714 }
4715
4716 // If this is a signed shift right, and the high bit is modified
4717 // by the logical operation, do not perform the transformation.
4718 // The highBitSet boolean indicates the value of the high bit of
4719 // the constant which would cause it to be modified for this
4720 // operation.
4721 //
Chris Lattner830ed032006-01-06 07:22:22 +00004722 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004723 uint64_t Val = Op0C->getRawValue();
4724 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4725 }
4726
4727 if (isValid) {
4728 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4729
4730 Instruction *NewShift =
4731 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4732 Op0BO->getName());
4733 Op0BO->setName("");
4734 InsertNewInstBefore(NewShift, I);
4735
4736 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4737 NewRHS);
4738 }
4739 }
4740 }
4741 }
4742
Chris Lattnerad0124c2006-01-06 07:52:12 +00004743 // Find out if this is a shift of a shift by a constant.
4744 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004745 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00004746 ShiftOp = Op0SI;
4747 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4748 // If this is a noop-integer case of a shift instruction, use the shift.
4749 if (CI->getOperand(0)->getType()->isInteger() &&
4750 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4751 CI->getType()->getPrimitiveSizeInBits() &&
4752 isa<ShiftInst>(CI->getOperand(0))) {
4753 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4754 }
4755 }
4756
4757 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4758 // Find the operands and properties of the input shift. Note that the
4759 // signedness of the input shift may differ from the current shift if there
4760 // is a noop cast between the two.
4761 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4762 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00004763 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004764
4765 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4766
4767 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4768 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4769
4770 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4771 if (isLeftShift == isShiftOfLeftShift) {
4772 // Do not fold these shifts if the first one is signed and the second one
4773 // is unsigned and this is a right shift. Further, don't do any folding
4774 // on them.
4775 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4776 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004777
Chris Lattnerad0124c2006-01-06 07:52:12 +00004778 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4779 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4780 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00004781
Chris Lattnerad0124c2006-01-06 07:52:12 +00004782 Value *Op = ShiftOp->getOperand(0);
4783 if (isShiftOfSignedShift != isSignedShift)
4784 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4785 return new ShiftInst(I.getOpcode(), Op,
4786 ConstantUInt::get(Type::UByteTy, Amt));
4787 }
4788
4789 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4790 // signed types, we can only support the (A >> c1) << c2 configuration,
4791 // because it can not turn an arbitrary bit of A into a sign bit.
4792 if (isUnsignedShift || isLeftShift) {
4793 // Calculate bitmask for what gets shifted off the edge.
4794 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4795 if (isLeftShift)
4796 C = ConstantExpr::getShl(C, ShiftAmt1C);
4797 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00004798 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004799
4800 Value *Op = ShiftOp->getOperand(0);
4801 if (isShiftOfSignedShift != isSignedShift)
4802 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4803
4804 Instruction *Mask =
4805 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4806 InsertNewInstBefore(Mask, I);
4807
4808 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00004809 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004810 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00004811 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004812 return new ShiftInst(I.getOpcode(), Mask,
4813 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004814 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4815 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4816 // Make sure to emit an unsigned shift right, not a signed one.
4817 Mask = InsertNewInstBefore(new CastInst(Mask,
4818 Mask->getType()->getUnsignedVersion(),
4819 Op->getName()), I);
4820 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00004821 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004822 InsertNewInstBefore(Mask, I);
4823 return new CastInst(Mask, I.getType());
4824 } else {
4825 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4826 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4827 }
4828 } else {
4829 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4830 Op = InsertNewInstBefore(new CastInst(Mask,
4831 I.getType()->getSignedVersion(),
4832 Mask->getName()), I);
4833 Instruction *Shift =
4834 new ShiftInst(ShiftOp->getOpcode(), Op,
4835 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4836 InsertNewInstBefore(Shift, I);
4837
4838 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4839 C = ConstantExpr::getShl(C, Op1);
4840 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4841 InsertNewInstBefore(Mask, I);
4842 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00004843 }
4844 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00004845 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00004846 // this case, C1 == C2 and C1 is 8, 16, or 32.
4847 if (ShiftAmt1 == ShiftAmt2) {
4848 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00004849 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004850 case 8 : SExtType = Type::SByteTy; break;
4851 case 16: SExtType = Type::ShortTy; break;
4852 case 32: SExtType = Type::IntTy; break;
4853 }
4854
4855 if (SExtType) {
4856 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4857 SExtType, "sext");
4858 InsertNewInstBefore(NewTrunc, I);
4859 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00004860 }
Chris Lattner11021cb2005-09-18 05:12:10 +00004861 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00004862 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004863 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004864 return 0;
4865}
4866
Chris Lattnera1be5662002-05-02 17:06:02 +00004867
Chris Lattnercfd65102005-10-29 04:36:15 +00004868/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4869/// expression. If so, decompose it, returning some value X, such that Val is
4870/// X*Scale+Offset.
4871///
4872static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4873 unsigned &Offset) {
4874 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4875 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4876 Offset = CI->getValue();
4877 Scale = 1;
4878 return ConstantUInt::get(Type::UIntTy, 0);
4879 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4880 if (I->getNumOperands() == 2) {
4881 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4882 if (I->getOpcode() == Instruction::Shl) {
4883 // This is a value scaled by '1 << the shift amt'.
4884 Scale = 1U << CUI->getValue();
4885 Offset = 0;
4886 return I->getOperand(0);
4887 } else if (I->getOpcode() == Instruction::Mul) {
4888 // This value is scaled by 'CUI'.
4889 Scale = CUI->getValue();
4890 Offset = 0;
4891 return I->getOperand(0);
4892 } else if (I->getOpcode() == Instruction::Add) {
4893 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4894 // divisible by C2.
4895 unsigned SubScale;
4896 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4897 Offset);
4898 Offset += CUI->getValue();
4899 if (SubScale > 1 && (Offset % SubScale == 0)) {
4900 Scale = SubScale;
4901 return SubVal;
4902 }
4903 }
4904 }
4905 }
4906 }
4907
4908 // Otherwise, we can't look past this.
4909 Scale = 1;
4910 Offset = 0;
4911 return Val;
4912}
4913
4914
Chris Lattnerb3f83972005-10-24 06:03:58 +00004915/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4916/// try to eliminate the cast by moving the type information into the alloc.
4917Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4918 AllocationInst &AI) {
4919 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004920 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004921
Chris Lattnerb53c2382005-10-24 06:22:12 +00004922 // Remove any uses of AI that are dead.
4923 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4924 std::vector<Instruction*> DeadUsers;
4925 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4926 Instruction *User = cast<Instruction>(*UI++);
4927 if (isInstructionTriviallyDead(User)) {
4928 while (UI != E && *UI == User)
4929 ++UI; // If this instruction uses AI more than once, don't break UI.
4930
4931 // Add operands to the worklist.
4932 AddUsesToWorkList(*User);
4933 ++NumDeadInst;
4934 DEBUG(std::cerr << "IC: DCE: " << *User);
4935
4936 User->eraseFromParent();
4937 removeFromWorkList(User);
4938 }
4939 }
4940
Chris Lattnerb3f83972005-10-24 06:03:58 +00004941 // Get the type really allocated and the type casted to.
4942 const Type *AllocElTy = AI.getAllocatedType();
4943 const Type *CastElTy = PTy->getElementType();
4944 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004945
4946 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4947 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4948 if (CastElTyAlign < AllocElTyAlign) return 0;
4949
Chris Lattner39387a52005-10-24 06:35:18 +00004950 // If the allocation has multiple uses, only promote it if we are strictly
4951 // increasing the alignment of the resultant allocation. If we keep it the
4952 // same, we open the door to infinite loops of various kinds.
4953 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4954
Chris Lattnerb3f83972005-10-24 06:03:58 +00004955 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4956 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004957 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004958
Chris Lattner455fcc82005-10-29 03:19:53 +00004959 // See if we can satisfy the modulus by pulling a scale out of the array
4960 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004961 unsigned ArraySizeScale, ArrayOffset;
4962 Value *NumElements = // See if the array size is a decomposable linear expr.
4963 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4964
Chris Lattner455fcc82005-10-29 03:19:53 +00004965 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4966 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004967 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4968 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004969
Chris Lattner455fcc82005-10-29 03:19:53 +00004970 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4971 Value *Amt = 0;
4972 if (Scale == 1) {
4973 Amt = NumElements;
4974 } else {
4975 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4976 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4977 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4978 else if (Scale != 1) {
4979 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4980 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004981 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004982 }
4983
Chris Lattnercfd65102005-10-29 04:36:15 +00004984 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4985 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4986 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4987 Amt = InsertNewInstBefore(Tmp, AI);
4988 }
4989
Chris Lattnerb3f83972005-10-24 06:03:58 +00004990 std::string Name = AI.getName(); AI.setName("");
4991 AllocationInst *New;
4992 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004993 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004994 else
Nate Begeman14b05292005-11-05 09:21:28 +00004995 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004996 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004997
4998 // If the allocation has multiple uses, insert a cast and change all things
4999 // that used it to use the new cast. This will also hack on CI, but it will
5000 // die soon.
5001 if (!AI.hasOneUse()) {
5002 AddUsesToWorkList(AI);
5003 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5004 InsertNewInstBefore(NewCast, AI);
5005 AI.replaceAllUsesWith(NewCast);
5006 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00005007 return ReplaceInstUsesWith(CI, New);
5008}
5009
Chris Lattner70074e02006-05-13 02:06:03 +00005010/// CanEvaluateInDifferentType - Return true if we can take the specified value
5011/// and return it without inserting any new casts. This is used by code that
5012/// tries to decide whether promoting or shrinking integer operations to wider
5013/// or smaller types will allow us to eliminate a truncate or extend.
5014static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5015 int &NumCastsRemoved) {
5016 if (isa<Constant>(V)) return true;
5017
5018 Instruction *I = dyn_cast<Instruction>(V);
5019 if (!I || !I->hasOneUse()) return false;
5020
5021 switch (I->getOpcode()) {
5022 case Instruction::And:
5023 case Instruction::Or:
5024 case Instruction::Xor:
5025 // These operators can all arbitrarily be extended or truncated.
5026 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5027 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5028 case Instruction::Cast:
5029 // If this is a cast from the destination type, we can trivially eliminate
5030 // it, and this will remove a cast overall.
5031 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00005032 // If the first operand is itself a cast, and is eliminable, do not count
5033 // this as an eliminable cast. We would prefer to eliminate those two
5034 // casts first.
5035 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5036 return true;
5037
Chris Lattner70074e02006-05-13 02:06:03 +00005038 ++NumCastsRemoved;
5039 return true;
5040 }
5041 // TODO: Can handle more cases here.
5042 break;
5043 }
5044
5045 return false;
5046}
5047
5048/// EvaluateInDifferentType - Given an expression that
5049/// CanEvaluateInDifferentType returns true for, actually insert the code to
5050/// evaluate the expression.
5051Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5052 if (Constant *C = dyn_cast<Constant>(V))
5053 return ConstantExpr::getCast(C, Ty);
5054
5055 // Otherwise, it must be an instruction.
5056 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00005057 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00005058 switch (I->getOpcode()) {
5059 case Instruction::And:
5060 case Instruction::Or:
5061 case Instruction::Xor: {
5062 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5063 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5064 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5065 LHS, RHS, I->getName());
5066 break;
5067 }
5068 case Instruction::Cast:
5069 // If this is a cast from the destination type, return the input.
5070 if (I->getOperand(0)->getType() == Ty)
5071 return I->getOperand(0);
5072
5073 // TODO: Can handle more cases here.
5074 assert(0 && "Unreachable!");
5075 break;
5076 }
5077
5078 return InsertNewInstBefore(Res, *I);
5079}
5080
Chris Lattnerb3f83972005-10-24 06:03:58 +00005081
Chris Lattnera1be5662002-05-02 17:06:02 +00005082// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005083//
Chris Lattner7e708292002-06-25 16:13:24 +00005084Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00005085 Value *Src = CI.getOperand(0);
5086
Chris Lattnera1be5662002-05-02 17:06:02 +00005087 // If the user is casting a value to the same type, eliminate this cast
5088 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00005089 if (CI.getType() == Src->getType())
5090 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00005091
Chris Lattnere87597f2004-10-16 18:11:37 +00005092 if (isa<UndefValue>(Src)) // cast undef -> undef
5093 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5094
Chris Lattnera1be5662002-05-02 17:06:02 +00005095 // If casting the result of another cast instruction, try to eliminate this
5096 // one!
5097 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00005098 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5099 Value *A = CSrc->getOperand(0);
5100 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5101 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00005102 // This instruction now refers directly to the cast's src operand. This
5103 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00005104 CI.setOperand(0, CSrc->getOperand(0));
5105 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00005106 }
5107
Chris Lattner8fd217c2002-08-02 20:00:25 +00005108 // If this is an A->B->A cast, and we are dealing with integral types, try
5109 // to convert this into a logical 'and' instruction.
5110 //
Misha Brukmanfd939082005-04-21 23:48:37 +00005111 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00005112 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00005113 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00005114 CSrc->getType()->getPrimitiveSizeInBits() <
5115 CI.getType()->getPrimitiveSizeInBits()&&
5116 A->getType()->getPrimitiveSizeInBits() ==
5117 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00005118 assert(CSrc->getType() != Type::ULongTy &&
5119 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00005120 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00005121 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5122 AndValue);
5123 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5124 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5125 if (And->getType() != CI.getType()) {
5126 And->setName(CSrc->getName()+".mask");
5127 InsertNewInstBefore(And, CI);
5128 And = new CastInst(And, CI.getType());
5129 }
5130 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00005131 }
5132 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00005133
Chris Lattnera710ddc2004-05-25 04:29:21 +00005134 // If this is a cast to bool, turn it into the appropriate setne instruction.
5135 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00005136 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00005137 Constant::getNullValue(CI.getOperand(0)->getType()));
5138
Chris Lattner6dce1a72006-02-07 06:56:34 +00005139 // See if we can simplify any instructions used by the LHS whose sole
5140 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00005141 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5142 uint64_t KnownZero, KnownOne;
5143 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5144 KnownZero, KnownOne))
5145 return &CI;
5146 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00005147
Chris Lattner797249b2003-06-21 23:12:02 +00005148 // If casting the result of a getelementptr instruction with no offset, turn
5149 // this into a cast of the original pointer!
5150 //
Chris Lattner79d35b32003-06-23 21:59:52 +00005151 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00005152 bool AllZeroOperands = true;
5153 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5154 if (!isa<Constant>(GEP->getOperand(i)) ||
5155 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5156 AllZeroOperands = false;
5157 break;
5158 }
5159 if (AllZeroOperands) {
5160 CI.setOperand(0, GEP->getOperand(0));
5161 return &CI;
5162 }
5163 }
5164
Chris Lattnerbc61e662003-11-02 05:57:39 +00005165 // If we are casting a malloc or alloca to a pointer to a type of the same
5166 // size, rewrite the allocation instruction to allocate the "right" type.
5167 //
5168 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00005169 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5170 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005171
Chris Lattner6e7ba452005-01-01 16:22:27 +00005172 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5173 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5174 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00005175 if (isa<PHINode>(Src))
5176 if (Instruction *NV = FoldOpIntoPhi(CI))
5177 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00005178
5179 // If the source and destination are pointers, and this cast is equivalent to
5180 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5181 // This can enhance SROA and other transforms that want type-safe pointers.
5182 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5183 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5184 const Type *DstTy = DstPTy->getElementType();
5185 const Type *SrcTy = SrcPTy->getElementType();
5186
5187 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5188 unsigned NumZeros = 0;
5189 while (SrcTy != DstTy &&
Chris Lattner63d32202006-09-11 21:43:16 +00005190 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5191 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattner9fb92132006-04-12 18:09:35 +00005192 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5193 ++NumZeros;
5194 }
Chris Lattner4e998b22004-09-29 05:07:12 +00005195
Chris Lattner9fb92132006-04-12 18:09:35 +00005196 // If we found a path from the src to dest, create the getelementptr now.
5197 if (SrcTy == DstTy) {
5198 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5199 return new GetElementPtrInst(Src, Idxs);
5200 }
5201 }
5202
Chris Lattner24c8e382003-07-24 17:35:25 +00005203 // If the source value is an instruction with only this use, we can attempt to
5204 // propagate the cast into the instruction. Also, only handle integral types
5205 // for now.
Chris Lattner01575b72006-05-25 23:24:33 +00005206 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerfd059242003-10-15 16:48:29 +00005207 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00005208 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner70074e02006-05-13 02:06:03 +00005209
5210 int NumCastsRemoved = 0;
5211 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5212 // If this cast is a truncate, evaluting in a different type always
5213 // eliminates the cast, so it is always a win. If this is a noop-cast
5214 // this just removes a noop cast which isn't pointful, but simplifies
5215 // the code. If this is a zero-extension, we need to do an AND to
5216 // maintain the clear top-part of the computation, so we require that
5217 // the input have eliminated at least one cast. If this is a sign
5218 // extension, we insert two new casts (to do the extension) so we
5219 // require that two casts have been eliminated.
5220 bool DoXForm;
5221 switch (getCastType(Src->getType(), CI.getType())) {
5222 default: assert(0 && "Unknown cast type!");
5223 case Noop:
5224 case Truncate:
5225 DoXForm = true;
5226 break;
5227 case Zeroext:
5228 DoXForm = NumCastsRemoved >= 1;
5229 break;
5230 case Signext:
5231 DoXForm = NumCastsRemoved >= 2;
5232 break;
5233 }
5234
5235 if (DoXForm) {
5236 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5237 assert(Res->getType() == CI.getType());
5238 switch (getCastType(Src->getType(), CI.getType())) {
5239 default: assert(0 && "Unknown cast type!");
5240 case Noop:
5241 case Truncate:
5242 // Just replace this cast with the result.
5243 return ReplaceInstUsesWith(CI, Res);
5244 case Zeroext: {
5245 // We need to emit an AND to clear the high bits.
5246 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5247 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5248 assert(SrcBitSize < DestBitSize && "Not a zext?");
5249 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5250 C = ConstantExpr::getCast(C, CI.getType());
5251 return BinaryOperator::createAnd(Res, C);
5252 }
5253 case Signext:
5254 // We need to emit a cast to truncate, then a cast to sext.
5255 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5256 CI.getType());
5257 }
5258 }
5259 }
5260
Chris Lattner24c8e382003-07-24 17:35:25 +00005261 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005262 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5263 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00005264
5265 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5266 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5267
5268 switch (SrcI->getOpcode()) {
5269 case Instruction::Add:
5270 case Instruction::Mul:
5271 case Instruction::And:
5272 case Instruction::Or:
5273 case Instruction::Xor:
5274 // If we are discarding information, or just changing the sign, rewrite.
5275 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5276 // Don't insert two casts if they cannot be eliminated. We allow two
5277 // casts to be inserted if the sizes are the same. This could only be
5278 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00005279 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5280 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00005281 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5282 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5283 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5284 ->getOpcode(), Op0c, Op1c);
5285 }
5286 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00005287
5288 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5289 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5290 Op1 == ConstantBool::True &&
5291 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5292 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5293 return BinaryOperator::createXor(New,
5294 ConstantInt::get(CI.getType(), 1));
5295 }
Chris Lattner24c8e382003-07-24 17:35:25 +00005296 break;
5297 case Instruction::Shl:
5298 // Allow changing the sign of the source operand. Do not allow changing
5299 // the size of the shift, UNLESS the shift amount is a constant. We
5300 // mush not change variable sized shifts to a smaller size, because it
5301 // is undefined to shift more bits out than exist in the value.
5302 if (DestBitSize == SrcBitSize ||
5303 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5304 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5305 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5306 }
5307 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00005308 case Instruction::Shr:
5309 // If this is a signed shr, and if all bits shifted in are about to be
5310 // truncated off, turn it into an unsigned shr to allow greater
5311 // simplifications.
5312 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5313 isa<ConstantInt>(Op1)) {
5314 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5315 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5316 // Convert to unsigned.
5317 Value *N1 = InsertOperandCastBefore(Op0,
5318 Op0->getType()->getUnsignedVersion(), &CI);
5319 // Insert the new shift, which is now unsigned.
5320 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5321 Op1, Src->getName()), CI);
5322 return new CastInst(N1, CI.getType());
5323 }
5324 }
5325 break;
5326
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005327 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00005328 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005329 // We if we are just checking for a seteq of a single bit and casting it
5330 // to an integer. If so, shift the bit to the appropriate place then
5331 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00005332 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005333 uint64_t Op1CV = Op1C->getZExtValue();
5334 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5335 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5336 // cast (X == 1) to int --> X iff X has only the low bit set.
5337 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5338 // cast (X != 0) to int --> X iff X has only the low bit set.
5339 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5340 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5341 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5342 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5343 // If Op1C some other power of two, convert:
5344 uint64_t KnownZero, KnownOne;
5345 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5346 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5347
5348 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5349 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5350 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5351 // (X&4) == 2 --> false
5352 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00005353 Constant *Res = ConstantBool::get(isSetNE);
5354 Res = ConstantExpr::getCast(Res, CI.getType());
5355 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005356 }
5357
5358 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5359 Value *In = Op0;
5360 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00005361 // Perform an unsigned shr by shiftamt. Convert input to
5362 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00005363 if (In->getType()->isSigned())
5364 In = InsertNewInstBefore(new CastInst(In,
5365 In->getType()->getUnsignedVersion(), In->getName()),CI);
5366 // Insert the shift to put the result in the low bit.
5367 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005368 ConstantInt::get(Type::UByteTy, ShiftAmt),
5369 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005370 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005371
5372 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5373 Constant *One = ConstantInt::get(In->getType(), 1);
5374 In = BinaryOperator::createXor(In, One, "tmp");
5375 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005376 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005377
5378 if (CI.getType() == In->getType())
5379 return ReplaceInstUsesWith(CI, In);
5380 else
5381 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00005382 }
Chris Lattner693787a2005-05-04 19:10:26 +00005383 }
5384 }
5385 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00005386 }
5387 }
Chris Lattner01575b72006-05-25 23:24:33 +00005388
5389 if (SrcI->hasOneUse()) {
5390 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5391 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5392 // because the inputs are known to be a vector. Check to see if this is
5393 // a cast to a vector with the same # elts.
5394 if (isa<PackedType>(CI.getType()) &&
5395 cast<PackedType>(CI.getType())->getNumElements() ==
5396 SVI->getType()->getNumElements()) {
5397 CastInst *Tmp;
5398 // If either of the operands is a cast from CI.getType(), then
5399 // evaluating the shuffle in the casted destination's type will allow
5400 // us to eliminate at least one cast.
5401 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5402 Tmp->getOperand(0)->getType() == CI.getType()) ||
5403 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner18a4af22006-06-06 22:26:02 +00005404 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner01575b72006-05-25 23:24:33 +00005405 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5406 CI.getType(), &CI);
5407 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5408 CI.getType(), &CI);
5409 // Return a new shuffle vector. Use the same element ID's, as we
5410 // know the vector types match #elts.
5411 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5412 }
5413 }
5414 }
5415 }
5416 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005417
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005418 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005419}
5420
Chris Lattnere576b912004-04-09 23:46:01 +00005421/// GetSelectFoldableOperands - We want to turn code that looks like this:
5422/// %C = or %A, %B
5423/// %D = select %cond, %C, %A
5424/// into:
5425/// %C = select %cond, %B, 0
5426/// %D = or %A, %C
5427///
5428/// Assuming that the specified instruction is an operand to the select, return
5429/// a bitmask indicating which operands of this instruction are foldable if they
5430/// equal the other incoming value of the select.
5431///
5432static unsigned GetSelectFoldableOperands(Instruction *I) {
5433 switch (I->getOpcode()) {
5434 case Instruction::Add:
5435 case Instruction::Mul:
5436 case Instruction::And:
5437 case Instruction::Or:
5438 case Instruction::Xor:
5439 return 3; // Can fold through either operand.
5440 case Instruction::Sub: // Can only fold on the amount subtracted.
5441 case Instruction::Shl: // Can only fold on the shift amount.
5442 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005443 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005444 default:
5445 return 0; // Cannot fold
5446 }
5447}
5448
5449/// GetSelectFoldableConstant - For the same transformation as the previous
5450/// function, return the identity constant that goes into the select.
5451static Constant *GetSelectFoldableConstant(Instruction *I) {
5452 switch (I->getOpcode()) {
5453 default: assert(0 && "This cannot happen!"); abort();
5454 case Instruction::Add:
5455 case Instruction::Sub:
5456 case Instruction::Or:
5457 case Instruction::Xor:
5458 return Constant::getNullValue(I->getType());
5459 case Instruction::Shl:
5460 case Instruction::Shr:
5461 return Constant::getNullValue(Type::UByteTy);
5462 case Instruction::And:
5463 return ConstantInt::getAllOnesValue(I->getType());
5464 case Instruction::Mul:
5465 return ConstantInt::get(I->getType(), 1);
5466 }
5467}
5468
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005469/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5470/// have the same opcode and only one use each. Try to simplify this.
5471Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5472 Instruction *FI) {
5473 if (TI->getNumOperands() == 1) {
5474 // If this is a non-volatile load or a cast from the same type,
5475 // merge.
5476 if (TI->getOpcode() == Instruction::Cast) {
5477 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5478 return 0;
5479 } else {
5480 return 0; // unknown unary op.
5481 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005482
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005483 // Fold this by inserting a select from the input values.
5484 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5485 FI->getOperand(0), SI.getName()+".v");
5486 InsertNewInstBefore(NewSI, SI);
5487 return new CastInst(NewSI, TI->getType());
5488 }
5489
5490 // Only handle binary operators here.
5491 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5492 return 0;
5493
5494 // Figure out if the operations have any operands in common.
5495 Value *MatchOp, *OtherOpT, *OtherOpF;
5496 bool MatchIsOpZero;
5497 if (TI->getOperand(0) == FI->getOperand(0)) {
5498 MatchOp = TI->getOperand(0);
5499 OtherOpT = TI->getOperand(1);
5500 OtherOpF = FI->getOperand(1);
5501 MatchIsOpZero = true;
5502 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5503 MatchOp = TI->getOperand(1);
5504 OtherOpT = TI->getOperand(0);
5505 OtherOpF = FI->getOperand(0);
5506 MatchIsOpZero = false;
5507 } else if (!TI->isCommutative()) {
5508 return 0;
5509 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5510 MatchOp = TI->getOperand(0);
5511 OtherOpT = TI->getOperand(1);
5512 OtherOpF = FI->getOperand(0);
5513 MatchIsOpZero = true;
5514 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5515 MatchOp = TI->getOperand(1);
5516 OtherOpT = TI->getOperand(0);
5517 OtherOpF = FI->getOperand(1);
5518 MatchIsOpZero = true;
5519 } else {
5520 return 0;
5521 }
5522
5523 // If we reach here, they do have operations in common.
5524 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5525 OtherOpF, SI.getName()+".v");
5526 InsertNewInstBefore(NewSI, SI);
5527
5528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5529 if (MatchIsOpZero)
5530 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5531 else
5532 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5533 } else {
5534 if (MatchIsOpZero)
5535 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5536 else
5537 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5538 }
5539}
5540
Chris Lattner3d69f462004-03-12 05:52:32 +00005541Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005542 Value *CondVal = SI.getCondition();
5543 Value *TrueVal = SI.getTrueValue();
5544 Value *FalseVal = SI.getFalseValue();
5545
5546 // select true, X, Y -> X
5547 // select false, X, Y -> Y
5548 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00005549 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005550 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005551 else {
5552 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005553 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005554 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005555
5556 // select C, X, X -> X
5557 if (TrueVal == FalseVal)
5558 return ReplaceInstUsesWith(SI, TrueVal);
5559
Chris Lattnere87597f2004-10-16 18:11:37 +00005560 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5561 return ReplaceInstUsesWith(SI, FalseVal);
5562 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5563 return ReplaceInstUsesWith(SI, TrueVal);
5564 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5565 if (isa<Constant>(TrueVal))
5566 return ReplaceInstUsesWith(SI, TrueVal);
5567 else
5568 return ReplaceInstUsesWith(SI, FalseVal);
5569 }
5570
Chris Lattner0c199a72004-04-08 04:43:23 +00005571 if (SI.getType() == Type::BoolTy)
5572 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5573 if (C == ConstantBool::True) {
5574 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005575 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005576 } else {
5577 // Change: A = select B, false, C --> A = and !B, C
5578 Value *NotCond =
5579 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5580 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005581 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005582 }
5583 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5584 if (C == ConstantBool::False) {
5585 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005586 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005587 } else {
5588 // Change: A = select B, C, true --> A = or !B, C
5589 Value *NotCond =
5590 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5591 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005592 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005593 }
5594 }
5595
Chris Lattner2eefe512004-04-09 19:05:30 +00005596 // Selecting between two integer constants?
5597 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5598 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5599 // select C, 1, 0 -> cast C to int
5600 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5601 return new CastInst(CondVal, SI.getType());
5602 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5603 // select C, 0, 1 -> cast !C to int
5604 Value *NotCond =
5605 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005606 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00005607 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005608 }
Chris Lattner457dd822004-06-09 07:59:58 +00005609
5610 // If one of the constants is zero (we know they can't both be) and we
5611 // have a setcc instruction with zero, and we have an 'and' with the
5612 // non-constant value, eliminate this whole mess. This corresponds to
5613 // cases like this: ((X & 27) ? 27 : 0)
5614 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5615 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5616 if ((IC->getOpcode() == Instruction::SetEQ ||
5617 IC->getOpcode() == Instruction::SetNE) &&
5618 isa<ConstantInt>(IC->getOperand(1)) &&
5619 cast<Constant>(IC->getOperand(1))->isNullValue())
5620 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5621 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005622 isa<ConstantInt>(ICA->getOperand(1)) &&
5623 (ICA->getOperand(1) == TrueValC ||
5624 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005625 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5626 // Okay, now we know that everything is set up, we just don't
5627 // know whether we have a setne or seteq and whether the true or
5628 // false val is the zero.
5629 bool ShouldNotVal = !TrueValC->isNullValue();
5630 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5631 Value *V = ICA;
5632 if (ShouldNotVal)
5633 V = InsertNewInstBefore(BinaryOperator::create(
5634 Instruction::Xor, V, ICA->getOperand(1)), SI);
5635 return ReplaceInstUsesWith(SI, V);
5636 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005637 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005638
5639 // See if we are selecting two values based on a comparison of the two values.
5640 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5641 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5642 // Transform (X == Y) ? X : Y -> Y
5643 if (SCI->getOpcode() == Instruction::SetEQ)
5644 return ReplaceInstUsesWith(SI, FalseVal);
5645 // Transform (X != Y) ? X : Y -> X
5646 if (SCI->getOpcode() == Instruction::SetNE)
5647 return ReplaceInstUsesWith(SI, TrueVal);
5648 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5649
5650 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5651 // Transform (X == Y) ? Y : X -> X
5652 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00005653 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005654 // Transform (X != Y) ? Y : X -> Y
5655 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00005656 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005657 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5658 }
5659 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005660
Chris Lattner87875da2005-01-13 22:52:24 +00005661 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5662 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5663 if (TI->hasOneUse() && FI->hasOneUse()) {
5664 bool isInverse = false;
5665 Instruction *AddOp = 0, *SubOp = 0;
5666
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005667 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5668 if (TI->getOpcode() == FI->getOpcode())
5669 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5670 return IV;
5671
5672 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5673 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00005674 if (TI->getOpcode() == Instruction::Sub &&
5675 FI->getOpcode() == Instruction::Add) {
5676 AddOp = FI; SubOp = TI;
5677 } else if (FI->getOpcode() == Instruction::Sub &&
5678 TI->getOpcode() == Instruction::Add) {
5679 AddOp = TI; SubOp = FI;
5680 }
5681
5682 if (AddOp) {
5683 Value *OtherAddOp = 0;
5684 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5685 OtherAddOp = AddOp->getOperand(1);
5686 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5687 OtherAddOp = AddOp->getOperand(0);
5688 }
5689
5690 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00005691 // So at this point we know we have (Y -> OtherAddOp):
5692 // select C, (add X, Y), (sub X, Z)
5693 Value *NegVal; // Compute -Z
5694 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5695 NegVal = ConstantExpr::getNeg(C);
5696 } else {
5697 NegVal = InsertNewInstBefore(
5698 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00005699 }
Chris Lattner97f37a42006-02-24 18:05:58 +00005700
5701 Value *NewTrueOp = OtherAddOp;
5702 Value *NewFalseOp = NegVal;
5703 if (AddOp != TI)
5704 std::swap(NewTrueOp, NewFalseOp);
5705 Instruction *NewSel =
5706 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5707
5708 NewSel = InsertNewInstBefore(NewSel, SI);
5709 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005710 }
5711 }
5712 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005713
Chris Lattnere576b912004-04-09 23:46:01 +00005714 // See if we can fold the select into one of our operands.
5715 if (SI.getType()->isInteger()) {
5716 // See the comment above GetSelectFoldableOperands for a description of the
5717 // transformation we are doing here.
5718 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5719 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5720 !isa<Constant>(FalseVal))
5721 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5722 unsigned OpToFold = 0;
5723 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5724 OpToFold = 1;
5725 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5726 OpToFold = 2;
5727 }
5728
5729 if (OpToFold) {
5730 Constant *C = GetSelectFoldableConstant(TVI);
5731 std::string Name = TVI->getName(); TVI->setName("");
5732 Instruction *NewSel =
5733 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5734 Name);
5735 InsertNewInstBefore(NewSel, SI);
5736 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5737 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5738 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5739 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5740 else {
5741 assert(0 && "Unknown instruction!!");
5742 }
5743 }
5744 }
Chris Lattnera96879a2004-09-29 17:40:11 +00005745
Chris Lattnere576b912004-04-09 23:46:01 +00005746 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5747 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5748 !isa<Constant>(TrueVal))
5749 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5750 unsigned OpToFold = 0;
5751 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5752 OpToFold = 1;
5753 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5754 OpToFold = 2;
5755 }
5756
5757 if (OpToFold) {
5758 Constant *C = GetSelectFoldableConstant(FVI);
5759 std::string Name = FVI->getName(); FVI->setName("");
5760 Instruction *NewSel =
5761 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5762 Name);
5763 InsertNewInstBefore(NewSel, SI);
5764 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5765 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5766 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5767 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5768 else {
5769 assert(0 && "Unknown instruction!!");
5770 }
5771 }
5772 }
5773 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005774
5775 if (BinaryOperator::isNot(CondVal)) {
5776 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5777 SI.setOperand(1, FalseVal);
5778 SI.setOperand(2, TrueVal);
5779 return &SI;
5780 }
5781
Chris Lattner3d69f462004-03-12 05:52:32 +00005782 return 0;
5783}
5784
Chris Lattner95a959d2006-03-06 20:18:44 +00005785/// GetKnownAlignment - If the specified pointer has an alignment that we can
5786/// determine, return it, otherwise return 0.
5787static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5788 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5789 unsigned Align = GV->getAlignment();
5790 if (Align == 0 && TD)
5791 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5792 return Align;
5793 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5794 unsigned Align = AI->getAlignment();
5795 if (Align == 0 && TD) {
5796 if (isa<AllocaInst>(AI))
5797 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5798 else if (isa<MallocInst>(AI)) {
5799 // Malloc returns maximally aligned memory.
5800 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5801 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5802 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5803 }
5804 }
5805 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00005806 } else if (isa<CastInst>(V) ||
5807 (isa<ConstantExpr>(V) &&
5808 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5809 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005810 if (isa<PointerType>(CI->getOperand(0)->getType()))
5811 return GetKnownAlignment(CI->getOperand(0), TD);
5812 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00005813 } else if (isa<GetElementPtrInst>(V) ||
5814 (isa<ConstantExpr>(V) &&
5815 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5816 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005817 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5818 if (BaseAlignment == 0) return 0;
5819
5820 // If all indexes are zero, it is just the alignment of the base pointer.
5821 bool AllZeroOperands = true;
5822 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5823 if (!isa<Constant>(GEPI->getOperand(i)) ||
5824 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5825 AllZeroOperands = false;
5826 break;
5827 }
5828 if (AllZeroOperands)
5829 return BaseAlignment;
5830
5831 // Otherwise, if the base alignment is >= the alignment we expect for the
5832 // base pointer type, then we know that the resultant pointer is aligned at
5833 // least as much as its type requires.
5834 if (!TD) return 0;
5835
5836 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5837 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00005838 <= BaseAlignment) {
5839 const Type *GEPTy = GEPI->getType();
5840 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5841 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005842 return 0;
5843 }
5844 return 0;
5845}
5846
Chris Lattner3d69f462004-03-12 05:52:32 +00005847
Chris Lattner8b0ea312006-01-13 20:11:04 +00005848/// visitCallInst - CallInst simplification. This mostly only handles folding
5849/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5850/// the heavy lifting.
5851///
Chris Lattner9fe38862003-06-19 17:00:31 +00005852Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00005853 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5854 if (!II) return visitCallSite(&CI);
5855
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005856 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5857 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005858 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005859 bool Changed = false;
5860
5861 // memmove/cpy/set of zero bytes is a noop.
5862 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5863 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5864
Chris Lattner35b9e482004-10-12 04:52:52 +00005865 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5866 if (CI->getRawValue() == 1) {
5867 // Replace the instruction with just byte operations. We would
5868 // transform other cases to loads/stores, but we don't know if
5869 // alignment is sufficient.
5870 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005871 }
5872
Chris Lattner35b9e482004-10-12 04:52:52 +00005873 // If we have a memmove and the source operation is a constant global,
5874 // then the source and dest pointers can't alias, so we can change this
5875 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00005876 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005877 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5878 if (GVSrc->isConstant()) {
5879 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00005880 const char *Name;
5881 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5882 Type::UIntTy)
5883 Name = "llvm.memcpy.i32";
5884 else
5885 Name = "llvm.memcpy.i64";
5886 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00005887 CI.getCalledFunction()->getFunctionType());
5888 CI.setOperand(0, MemCpy);
5889 Changed = true;
5890 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005891 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005892
Chris Lattner95a959d2006-03-06 20:18:44 +00005893 // If we can determine a pointer alignment that is bigger than currently
5894 // set, update the alignment.
5895 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5896 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5897 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5898 unsigned Align = std::min(Alignment1, Alignment2);
5899 if (MI->getAlignment()->getRawValue() < Align) {
5900 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5901 Changed = true;
5902 }
5903 } else if (isa<MemSetInst>(MI)) {
5904 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5905 if (MI->getAlignment()->getRawValue() < Alignment) {
5906 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5907 Changed = true;
5908 }
5909 }
5910
Chris Lattner8b0ea312006-01-13 20:11:04 +00005911 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00005912 } else {
5913 switch (II->getIntrinsicID()) {
5914 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00005915 case Intrinsic::ppc_altivec_lvx:
5916 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005917 case Intrinsic::x86_sse_loadu_ps:
5918 case Intrinsic::x86_sse2_loadu_pd:
5919 case Intrinsic::x86_sse2_loadu_dq:
5920 // Turn PPC lvx -> load if the pointer is known aligned.
5921 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00005922 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005923 Value *Ptr = InsertCastBefore(II->getOperand(1),
5924 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005925 return new LoadInst(Ptr);
5926 }
5927 break;
5928 case Intrinsic::ppc_altivec_stvx:
5929 case Intrinsic::ppc_altivec_stvxl:
5930 // Turn stvx -> store if the pointer is known aligned.
5931 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005932 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5933 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005934 return new StoreInst(II->getOperand(1), Ptr);
5935 }
5936 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005937 case Intrinsic::x86_sse_storeu_ps:
5938 case Intrinsic::x86_sse2_storeu_pd:
5939 case Intrinsic::x86_sse2_storeu_dq:
5940 case Intrinsic::x86_sse2_storel_dq:
5941 // Turn X86 storeu -> store if the pointer is known aligned.
5942 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5943 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5944 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5945 return new StoreInst(II->getOperand(2), Ptr);
5946 }
5947 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00005948 case Intrinsic::ppc_altivec_vperm:
5949 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5950 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5951 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5952
5953 // Check that all of the elements are integer constants or undefs.
5954 bool AllEltsOk = true;
5955 for (unsigned i = 0; i != 16; ++i) {
5956 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5957 !isa<UndefValue>(Mask->getOperand(i))) {
5958 AllEltsOk = false;
5959 break;
5960 }
5961 }
5962
5963 if (AllEltsOk) {
5964 // Cast the input vectors to byte vectors.
5965 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5966 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5967 Value *Result = UndefValue::get(Op0->getType());
5968
5969 // Only extract each element once.
5970 Value *ExtractedElts[32];
5971 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5972
5973 for (unsigned i = 0; i != 16; ++i) {
5974 if (isa<UndefValue>(Mask->getOperand(i)))
5975 continue;
5976 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5977 Idx &= 31; // Match the hardware behavior.
5978
5979 if (ExtractedElts[Idx] == 0) {
5980 Instruction *Elt =
5981 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5982 ConstantUInt::get(Type::UIntTy, Idx&15),
5983 "tmp");
5984 InsertNewInstBefore(Elt, CI);
5985 ExtractedElts[Idx] = Elt;
5986 }
5987
5988 // Insert this value into the result vector.
5989 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5990 ConstantUInt::get(Type::UIntTy, i),
5991 "tmp");
5992 InsertNewInstBefore(cast<Instruction>(Result), CI);
5993 }
5994 return new CastInst(Result, CI.getType());
5995 }
5996 }
5997 break;
5998
Chris Lattnera728ddc2006-01-13 21:28:09 +00005999 case Intrinsic::stackrestore: {
6000 // If the save is right next to the restore, remove the restore. This can
6001 // happen when variable allocas are DCE'd.
6002 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6003 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6004 BasicBlock::iterator BI = SS;
6005 if (&*++BI == II)
6006 return EraseInstFromFunction(CI);
6007 }
6008 }
6009
6010 // If the stack restore is in a return/unwind block and if there are no
6011 // allocas or calls between the restore and the return, nuke the restore.
6012 TerminatorInst *TI = II->getParent()->getTerminator();
6013 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6014 BasicBlock::iterator BI = II;
6015 bool CannotRemove = false;
6016 for (++BI; &*BI != TI; ++BI) {
6017 if (isa<AllocaInst>(BI) ||
6018 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6019 CannotRemove = true;
6020 break;
6021 }
6022 }
6023 if (!CannotRemove)
6024 return EraseInstFromFunction(CI);
6025 }
6026 break;
6027 }
6028 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006029 }
6030
Chris Lattner8b0ea312006-01-13 20:11:04 +00006031 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006032}
6033
6034// InvokeInst simplification
6035//
6036Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00006037 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006038}
6039
Chris Lattnera44d8a22003-10-07 22:32:43 +00006040// visitCallSite - Improvements for call and invoke instructions.
6041//
6042Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00006043 bool Changed = false;
6044
6045 // If the callee is a constexpr cast of a function, attempt to move the cast
6046 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00006047 if (transformConstExprCastCall(CS)) return 0;
6048
Chris Lattner6c266db2003-10-07 22:54:13 +00006049 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00006050
Chris Lattner08b22ec2005-05-13 07:09:09 +00006051 if (Function *CalleeF = dyn_cast<Function>(Callee))
6052 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6053 Instruction *OldCall = CS.getInstruction();
6054 // If the call and callee calling conventions don't match, this call must
6055 // be unreachable, as the call is undefined.
6056 new StoreInst(ConstantBool::True,
6057 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6058 if (!OldCall->use_empty())
6059 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6060 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6061 return EraseInstFromFunction(*OldCall);
6062 return 0;
6063 }
6064
Chris Lattner17be6352004-10-18 02:59:09 +00006065 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6066 // This instruction is not reachable, just remove it. We insert a store to
6067 // undef so that we know that this code is not reachable, despite the fact
6068 // that we can't modify the CFG here.
6069 new StoreInst(ConstantBool::True,
6070 UndefValue::get(PointerType::get(Type::BoolTy)),
6071 CS.getInstruction());
6072
6073 if (!CS.getInstruction()->use_empty())
6074 CS.getInstruction()->
6075 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6076
6077 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6078 // Don't break the CFG, insert a dummy cond branch.
6079 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6080 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00006081 }
Chris Lattner17be6352004-10-18 02:59:09 +00006082 return EraseInstFromFunction(*CS.getInstruction());
6083 }
Chris Lattnere87597f2004-10-16 18:11:37 +00006084
Chris Lattner6c266db2003-10-07 22:54:13 +00006085 const PointerType *PTy = cast<PointerType>(Callee->getType());
6086 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6087 if (FTy->isVarArg()) {
6088 // See if we can optimize any arguments passed through the varargs area of
6089 // the call.
6090 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6091 E = CS.arg_end(); I != E; ++I)
6092 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6093 // If this cast does not effect the value passed through the varargs
6094 // area, we can eliminate the use of the cast.
6095 Value *Op = CI->getOperand(0);
6096 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6097 *I = Op;
6098 Changed = true;
6099 }
6100 }
6101 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006102
Chris Lattner6c266db2003-10-07 22:54:13 +00006103 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00006104}
6105
Chris Lattner9fe38862003-06-19 17:00:31 +00006106// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6107// attempt to move the cast to the arguments of the call/invoke.
6108//
6109bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6110 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6111 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00006112 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00006113 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00006114 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00006115 Instruction *Caller = CS.getInstruction();
6116
6117 // Okay, this is a cast from a function to a different type. Unless doing so
6118 // would cause a type conversion of one of our arguments, change this call to
6119 // be a direct call with arguments casted to the appropriate types.
6120 //
6121 const FunctionType *FT = Callee->getFunctionType();
6122 const Type *OldRetTy = Caller->getType();
6123
Chris Lattnerf78616b2004-01-14 06:06:08 +00006124 // Check to see if we are changing the return type...
6125 if (OldRetTy != FT->getReturnType()) {
6126 if (Callee->isExternal() &&
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006127 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6128 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharth7a31b972006-04-20 15:41:37 +00006129 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006130 && !Caller->use_empty())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006131 return false; // Cannot transform this return value...
6132
6133 // If the callsite is an invoke instruction, and the return value is used by
6134 // a PHI node in a successor, we cannot change the return type of the call
6135 // because there is no place to put the cast instruction (without breaking
6136 // the critical edge). Bail out in this case.
6137 if (!Caller->use_empty())
6138 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6139 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6140 UI != E; ++UI)
6141 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6142 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006143 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006144 return false;
6145 }
Chris Lattner9fe38862003-06-19 17:00:31 +00006146
6147 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6148 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006149
Chris Lattner9fe38862003-06-19 17:00:31 +00006150 CallSite::arg_iterator AI = CS.arg_begin();
6151 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6152 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006153 const Type *ActTy = (*AI)->getType();
6154 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6155 //Either we can cast directly, or we can upconvert the argument
6156 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6157 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6158 ParamTy->isSigned() == ActTy->isSigned() &&
6159 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6160 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6161 c->getValue() > 0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006162 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00006163 }
6164
6165 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6166 Callee->isExternal())
6167 return false; // Do not delete arguments unless we have a function body...
6168
6169 // Okay, we decided that this is a safe thing to do: go ahead and start
6170 // inserting cast instructions as necessary...
6171 std::vector<Value*> Args;
6172 Args.reserve(NumActualArgs);
6173
6174 AI = CS.arg_begin();
6175 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6176 const Type *ParamTy = FT->getParamType(i);
6177 if ((*AI)->getType() == ParamTy) {
6178 Args.push_back(*AI);
6179 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00006180 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6181 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00006182 }
6183 }
6184
6185 // If the function takes more arguments than the call was taking, add them
6186 // now...
6187 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6188 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6189
6190 // If we are removing arguments to the function, emit an obnoxious warning...
6191 if (FT->getNumParams() < NumActualArgs)
6192 if (!FT->isVarArg()) {
6193 std::cerr << "WARNING: While resolving call to function '"
6194 << Callee->getName() << "' arguments were dropped!\n";
6195 } else {
6196 // Add all of the arguments in their promoted form to the arg list...
6197 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6198 const Type *PTy = getPromotedType((*AI)->getType());
6199 if (PTy != (*AI)->getType()) {
6200 // Must promote to pass through va_arg area!
6201 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6202 InsertNewInstBefore(Cast, *Caller);
6203 Args.push_back(Cast);
6204 } else {
6205 Args.push_back(*AI);
6206 }
6207 }
6208 }
6209
6210 if (FT->getReturnType() == Type::VoidTy)
6211 Caller->setName(""); // Void type should not have a name...
6212
6213 Instruction *NC;
6214 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006215 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00006216 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00006217 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00006218 } else {
6219 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00006220 if (cast<CallInst>(Caller)->isTailCall())
6221 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00006222 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00006223 }
6224
6225 // Insert a cast of the return type as necessary...
6226 Value *NV = NC;
6227 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6228 if (NV->getType() != Type::VoidTy) {
6229 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00006230
6231 // If this is an invoke instruction, we should insert it after the first
6232 // non-phi, instruction in the normal successor block.
6233 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6234 BasicBlock::iterator I = II->getNormalDest()->begin();
6235 while (isa<PHINode>(I)) ++I;
6236 InsertNewInstBefore(NC, *I);
6237 } else {
6238 // Otherwise, it's a call, just insert cast right after the call instr
6239 InsertNewInstBefore(NC, *Caller);
6240 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006241 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00006242 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00006243 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00006244 }
6245 }
6246
6247 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6248 Caller->replaceAllUsesWith(NV);
6249 Caller->getParent()->getInstList().erase(Caller);
6250 removeFromWorkList(Caller);
6251 return true;
6252}
6253
6254
Chris Lattnerbac32862004-11-14 19:13:23 +00006255// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6256// operator and they all are only used by the PHI, PHI together their
6257// inputs, and do the operation once, to the result of the PHI.
6258Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6259 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6260
6261 // Scan the instruction, looking for input operations that can be folded away.
6262 // If all input operands to the phi are the same instruction (e.g. a cast from
6263 // the same type or "+42") we can pull the operation through the PHI, reducing
6264 // code size and simplifying code.
6265 Constant *ConstantOp = 0;
6266 const Type *CastSrcTy = 0;
6267 if (isa<CastInst>(FirstInst)) {
6268 CastSrcTy = FirstInst->getOperand(0)->getType();
6269 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6270 // Can fold binop or shift if the RHS is a constant.
6271 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6272 if (ConstantOp == 0) return 0;
6273 } else {
6274 return 0; // Cannot fold this operation.
6275 }
6276
6277 // Check to see if all arguments are the same operation.
6278 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6279 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6280 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6281 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6282 return 0;
6283 if (CastSrcTy) {
6284 if (I->getOperand(0)->getType() != CastSrcTy)
6285 return 0; // Cast operation must match.
6286 } else if (I->getOperand(1) != ConstantOp) {
6287 return 0;
6288 }
6289 }
6290
6291 // Okay, they are all the same operation. Create a new PHI node of the
6292 // correct type, and PHI together all of the LHS's of the instructions.
6293 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6294 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00006295 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00006296
6297 Value *InVal = FirstInst->getOperand(0);
6298 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00006299
6300 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00006301 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6302 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6303 if (NewInVal != InVal)
6304 InVal = 0;
6305 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6306 }
6307
6308 Value *PhiVal;
6309 if (InVal) {
6310 // The new PHI unions all of the same values together. This is really
6311 // common, so we handle it intelligently here for compile-time speed.
6312 PhiVal = InVal;
6313 delete NewPN;
6314 } else {
6315 InsertNewInstBefore(NewPN, PN);
6316 PhiVal = NewPN;
6317 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006318
Chris Lattnerbac32862004-11-14 19:13:23 +00006319 // Insert and return the new operation.
6320 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006321 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00006322 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006323 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006324 else
6325 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00006326 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006327}
Chris Lattnera1be5662002-05-02 17:06:02 +00006328
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006329/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6330/// that is dead.
6331static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6332 if (PN->use_empty()) return true;
6333 if (!PN->hasOneUse()) return false;
6334
6335 // Remember this node, and if we find the cycle, return.
6336 if (!PotentiallyDeadPHIs.insert(PN).second)
6337 return true;
6338
6339 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6340 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006341
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006342 return false;
6343}
6344
Chris Lattner473945d2002-05-06 18:06:38 +00006345// PHINode simplification
6346//
Chris Lattner7e708292002-06-25 16:13:24 +00006347Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00006348 // If LCSSA is around, don't mess with Phi nodes
6349 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00006350
Owen Anderson7e057142006-07-10 22:03:18 +00006351 if (Value *V = PN.hasConstantValue())
6352 return ReplaceInstUsesWith(PN, V);
6353
6354 // If the only user of this instruction is a cast instruction, and all of the
6355 // incoming values are constants, change this PHI to merge together the casted
6356 // constants.
6357 if (PN.hasOneUse())
6358 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6359 if (CI->getType() != PN.getType()) { // noop casts will be folded
6360 bool AllConstant = true;
6361 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6362 if (!isa<Constant>(PN.getIncomingValue(i))) {
6363 AllConstant = false;
6364 break;
6365 }
6366 if (AllConstant) {
6367 // Make a new PHI with all casted values.
6368 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6369 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6370 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6371 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6372 PN.getIncomingBlock(i));
6373 }
6374
6375 // Update the cast instruction.
6376 CI->setOperand(0, New);
6377 WorkList.push_back(CI); // revisit the cast instruction to fold.
6378 WorkList.push_back(New); // Make sure to revisit the new Phi
6379 return &PN; // PN is now dead!
6380 }
6381 }
6382
6383 // If all PHI operands are the same operation, pull them through the PHI,
6384 // reducing code size.
6385 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6386 PN.getIncomingValue(0)->hasOneUse())
6387 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6388 return Result;
6389
6390 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6391 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6392 // PHI)... break the cycle.
6393 if (PN.hasOneUse())
6394 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6395 std::set<PHINode*> PotentiallyDeadPHIs;
6396 PotentiallyDeadPHIs.insert(&PN);
6397 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6398 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6399 }
6400
Chris Lattner60921c92003-12-19 05:58:40 +00006401 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00006402}
6403
Chris Lattner28977af2004-04-05 01:30:19 +00006404static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6405 Instruction *InsertPoint,
6406 InstCombiner *IC) {
6407 unsigned PS = IC->getTargetData().getPointerSize();
6408 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00006409 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6410 // We must insert a cast to ensure we sign-extend.
6411 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6412 V->getName()), *InsertPoint);
6413 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6414 *InsertPoint);
6415}
6416
Chris Lattnera1be5662002-05-02 17:06:02 +00006417
Chris Lattner7e708292002-06-25 16:13:24 +00006418Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00006419 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00006420 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00006421 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006422 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00006423 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006424
Chris Lattnere87597f2004-10-16 18:11:37 +00006425 if (isa<UndefValue>(GEP.getOperand(0)))
6426 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6427
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006428 bool HasZeroPointerIndex = false;
6429 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6430 HasZeroPointerIndex = C->isNullValue();
6431
6432 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00006433 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00006434
Chris Lattner28977af2004-04-05 01:30:19 +00006435 // Eliminate unneeded casts for indices.
6436 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006437 gep_type_iterator GTI = gep_type_begin(GEP);
6438 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6439 if (isa<SequentialType>(*GTI)) {
6440 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6441 Value *Src = CI->getOperand(0);
6442 const Type *SrcTy = Src->getType();
6443 const Type *DestTy = CI->getType();
6444 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006445 if (SrcTy->getPrimitiveSizeInBits() ==
6446 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006447 // We can always eliminate a cast from ulong or long to the other.
6448 // We can always eliminate a cast from uint to int or the other on
6449 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00006450 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006451 MadeChange = true;
6452 GEP.setOperand(i, Src);
6453 }
6454 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6455 SrcTy->getPrimitiveSize() == 4) {
6456 // We can always eliminate a cast from int to [u]long. We can
6457 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6458 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00006459 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00006460 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006461 MadeChange = true;
6462 GEP.setOperand(i, Src);
6463 }
Chris Lattner28977af2004-04-05 01:30:19 +00006464 }
6465 }
6466 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006467 // If we are using a wider index than needed for this platform, shrink it
6468 // to what we need. If the incoming value needs a cast instruction,
6469 // insert it. This explicit cast can make subsequent optimizations more
6470 // obvious.
6471 Value *Op = GEP.getOperand(i);
6472 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00006473 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00006474 GEP.setOperand(i, ConstantExpr::getCast(C,
6475 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00006476 MadeChange = true;
6477 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006478 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6479 Op->getName()), GEP);
6480 GEP.setOperand(i, Op);
6481 MadeChange = true;
6482 }
Chris Lattner67769e52004-07-20 01:48:15 +00006483
6484 // If this is a constant idx, make sure to canonicalize it to be a signed
6485 // operand, otherwise CSE and other optimizations are pessimized.
6486 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6487 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6488 CUI->getType()->getSignedVersion()));
6489 MadeChange = true;
6490 }
Chris Lattner28977af2004-04-05 01:30:19 +00006491 }
6492 if (MadeChange) return &GEP;
6493
Chris Lattner90ac28c2002-08-02 19:29:35 +00006494 // Combine Indices - If the source pointer to this getelementptr instruction
6495 // is a getelementptr instruction, combine the indices of the two
6496 // getelementptr instructions into a single instruction.
6497 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00006498 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00006499 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00006500 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00006501
6502 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00006503 // Note that if our source is a gep chain itself that we wait for that
6504 // chain to be resolved before we perform this transformation. This
6505 // avoids us creating a TON of code in some cases.
6506 //
6507 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6508 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6509 return 0; // Wait until our source is folded to completion.
6510
Chris Lattner90ac28c2002-08-02 19:29:35 +00006511 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00006512
6513 // Find out whether the last index in the source GEP is a sequential idx.
6514 bool EndsWithSequential = false;
6515 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6516 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00006517 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00006518
Chris Lattner90ac28c2002-08-02 19:29:35 +00006519 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00006520 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00006521 // Replace: gep (gep %P, long B), long A, ...
6522 // With: T = long A+B; gep %P, T, ...
6523 //
Chris Lattner620ce142004-05-07 22:09:22 +00006524 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00006525 if (SO1 == Constant::getNullValue(SO1->getType())) {
6526 Sum = GO1;
6527 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6528 Sum = SO1;
6529 } else {
6530 // If they aren't the same type, convert both to an integer of the
6531 // target's pointer size.
6532 if (SO1->getType() != GO1->getType()) {
6533 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6534 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6535 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6536 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6537 } else {
6538 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00006539 if (SO1->getType()->getPrimitiveSize() == PS) {
6540 // Convert GO1 to SO1's type.
6541 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6542
6543 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6544 // Convert SO1 to GO1's type.
6545 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6546 } else {
6547 const Type *PT = TD->getIntPtrType();
6548 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6549 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6550 }
6551 }
6552 }
Chris Lattner620ce142004-05-07 22:09:22 +00006553 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6554 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6555 else {
Chris Lattner48595f12004-06-10 02:07:29 +00006556 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6557 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00006558 }
Chris Lattner28977af2004-04-05 01:30:19 +00006559 }
Chris Lattner620ce142004-05-07 22:09:22 +00006560
6561 // Recycle the GEP we already have if possible.
6562 if (SrcGEPOperands.size() == 2) {
6563 GEP.setOperand(0, SrcGEPOperands[0]);
6564 GEP.setOperand(1, Sum);
6565 return &GEP;
6566 } else {
6567 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6568 SrcGEPOperands.end()-1);
6569 Indices.push_back(Sum);
6570 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6571 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006572 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00006573 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006574 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00006575 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00006576 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6577 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00006578 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6579 }
6580
6581 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00006582 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00006583
Chris Lattner620ce142004-05-07 22:09:22 +00006584 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00006585 // GEP of global variable. If all of the indices for this GEP are
6586 // constants, we can promote this to a constexpr instead of an instruction.
6587
6588 // Scan for nonconstants...
6589 std::vector<Constant*> Indices;
6590 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6591 for (; I != E && isa<Constant>(*I); ++I)
6592 Indices.push_back(cast<Constant>(*I));
6593
6594 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00006595 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00006596
6597 // Replace all uses of the GEP with the new constexpr...
6598 return ReplaceInstUsesWith(GEP, CE);
6599 }
Chris Lattnereed48272005-09-13 00:40:14 +00006600 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6601 if (!isa<PointerType>(X->getType())) {
6602 // Not interesting. Source pointer must be a cast from pointer.
6603 } else if (HasZeroPointerIndex) {
6604 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6605 // into : GEP [10 x ubyte]* X, long 0, ...
6606 //
6607 // This occurs when the program declares an array extern like "int X[];"
6608 //
6609 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6610 const PointerType *XTy = cast<PointerType>(X->getType());
6611 if (const ArrayType *XATy =
6612 dyn_cast<ArrayType>(XTy->getElementType()))
6613 if (const ArrayType *CATy =
6614 dyn_cast<ArrayType>(CPTy->getElementType()))
6615 if (CATy->getElementType() == XATy->getElementType()) {
6616 // At this point, we know that the cast source type is a pointer
6617 // to an array of the same type as the destination pointer
6618 // array. Because the array type is never stepped over (there
6619 // is a leading zero) we can fold the cast into this GEP.
6620 GEP.setOperand(0, X);
6621 return &GEP;
6622 }
6623 } else if (GEP.getNumOperands() == 2) {
6624 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00006625 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6626 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00006627 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6628 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6629 if (isa<ArrayType>(SrcElTy) &&
6630 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6631 TD->getTypeSize(ResElTy)) {
6632 Value *V = InsertNewInstBefore(
6633 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6634 GEP.getOperand(1), GEP.getName()), GEP);
6635 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006636 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00006637
6638 // Transform things like:
6639 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6640 // (where tmp = 8*tmp2) into:
6641 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6642
6643 if (isa<ArrayType>(SrcElTy) &&
6644 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6645 uint64_t ArrayEltSize =
6646 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6647
6648 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6649 // allow either a mul, shift, or constant here.
6650 Value *NewIdx = 0;
6651 ConstantInt *Scale = 0;
6652 if (ArrayEltSize == 1) {
6653 NewIdx = GEP.getOperand(1);
6654 Scale = ConstantInt::get(NewIdx->getType(), 1);
6655 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00006656 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006657 Scale = CI;
6658 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6659 if (Inst->getOpcode() == Instruction::Shl &&
6660 isa<ConstantInt>(Inst->getOperand(1))) {
6661 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6662 if (Inst->getType()->isSigned())
6663 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6664 else
6665 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6666 NewIdx = Inst->getOperand(0);
6667 } else if (Inst->getOpcode() == Instruction::Mul &&
6668 isa<ConstantInt>(Inst->getOperand(1))) {
6669 Scale = cast<ConstantInt>(Inst->getOperand(1));
6670 NewIdx = Inst->getOperand(0);
6671 }
6672 }
6673
6674 // If the index will be to exactly the right offset with the scale taken
6675 // out, perform the transformation.
6676 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6677 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6678 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00006679 (int64_t)C->getRawValue() /
6680 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006681 else
6682 Scale = ConstantUInt::get(Scale->getType(),
6683 Scale->getRawValue() / ArrayEltSize);
6684 if (Scale->getRawValue() != 1) {
6685 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6686 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6687 NewIdx = InsertNewInstBefore(Sc, GEP);
6688 }
6689
6690 // Insert the new GEP instruction.
6691 Instruction *Idx =
6692 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6693 NewIdx, GEP.getName());
6694 Idx = InsertNewInstBefore(Idx, GEP);
6695 return new CastInst(Idx, GEP.getType());
6696 }
6697 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006698 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006699 }
6700
Chris Lattner8a2a3112001-12-14 16:52:21 +00006701 return 0;
6702}
6703
Chris Lattner0864acf2002-11-04 16:18:53 +00006704Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6705 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6706 if (AI.isArrayAllocation()) // Check C != 1
6707 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6708 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00006709 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00006710
6711 // Create and insert the replacement instruction...
6712 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00006713 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006714 else {
6715 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00006716 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006717 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006718
6719 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006720
Chris Lattner0864acf2002-11-04 16:18:53 +00006721 // Scan to the end of the allocation instructions, to skip over a block of
6722 // allocas if possible...
6723 //
6724 BasicBlock::iterator It = New;
6725 while (isa<AllocationInst>(*It)) ++It;
6726
6727 // Now that I is pointing to the first non-allocation-inst in the block,
6728 // insert our getelementptr instruction...
6729 //
Chris Lattner693787a2005-05-04 19:10:26 +00006730 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6731 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6732 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00006733
6734 // Now make everything use the getelementptr instead of the original
6735 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00006736 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00006737 } else if (isa<UndefValue>(AI.getArraySize())) {
6738 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00006739 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006740
6741 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6742 // Note that we only do this for alloca's, because malloc should allocate and
6743 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00006744 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00006745 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00006746 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6747
Chris Lattner0864acf2002-11-04 16:18:53 +00006748 return 0;
6749}
6750
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006751Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6752 Value *Op = FI.getOperand(0);
6753
6754 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6755 if (CastInst *CI = dyn_cast<CastInst>(Op))
6756 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6757 FI.setOperand(0, CI->getOperand(0));
6758 return &FI;
6759 }
6760
Chris Lattner17be6352004-10-18 02:59:09 +00006761 // free undef -> unreachable.
6762 if (isa<UndefValue>(Op)) {
6763 // Insert a new store to null because we cannot modify the CFG here.
6764 new StoreInst(ConstantBool::True,
6765 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6766 return EraseInstFromFunction(FI);
6767 }
6768
Chris Lattner6160e852004-02-28 04:57:37 +00006769 // If we have 'free null' delete the instruction. This can happen in stl code
6770 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00006771 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006772 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00006773
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006774 return 0;
6775}
6776
6777
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006778/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00006779static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6780 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00006781 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00006782
6783 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006784 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00006785 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006786
Chris Lattnera1c35382006-04-02 05:37:12 +00006787 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6788 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00006789 // If the source is an array, the code below will not succeed. Check to
6790 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6791 // constants.
6792 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6793 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6794 if (ASrcTy->getNumElements() != 0) {
6795 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6796 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6797 SrcTy = cast<PointerType>(CastOp->getType());
6798 SrcPTy = SrcTy->getElementType();
6799 }
6800
Chris Lattnera1c35382006-04-02 05:37:12 +00006801 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6802 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00006803 // Do not allow turning this into a load of an integer, which is then
6804 // casted to a pointer, this pessimizes pointer analysis a lot.
6805 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006806 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00006807 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00006808
Chris Lattnerf9527852005-01-31 04:50:46 +00006809 // Okay, we are casting from one integer or pointer type to another of
6810 // the same size. Instead of casting the pointer before the load, cast
6811 // the result of the loaded value.
6812 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6813 CI->getName(),
6814 LI.isVolatile()),LI);
6815 // Now cast the result of the load.
6816 return new CastInst(NewLoad, LI.getType());
6817 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00006818 }
6819 }
6820 return 0;
6821}
6822
Chris Lattnerc10aced2004-09-19 18:43:46 +00006823/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00006824/// from this value cannot trap. If it is not obviously safe to load from the
6825/// specified pointer, we do a quick local scan of the basic block containing
6826/// ScanFrom, to determine if the address is already accessed.
6827static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6828 // If it is an alloca or global variable, it is always safe to load from.
6829 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6830
6831 // Otherwise, be a little bit agressive by scanning the local block where we
6832 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006833 // from/to. If so, the previous load or store would have already trapped,
6834 // so there is no harm doing an extra load (also, CSE will later eliminate
6835 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00006836 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6837
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006838 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00006839 --BBI;
6840
6841 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6842 if (LI->getOperand(0) == V) return true;
6843 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6844 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00006845
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006846 }
Chris Lattner8a375202004-09-19 19:18:10 +00006847 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00006848}
6849
Chris Lattner833b8a42003-06-26 05:06:25 +00006850Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6851 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00006852
Chris Lattner37366c12005-05-01 04:24:53 +00006853 // load (cast X) --> cast (load X) iff safe
6854 if (CastInst *CI = dyn_cast<CastInst>(Op))
6855 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6856 return Res;
6857
6858 // None of the following transforms are legal for volatile loads.
6859 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00006860
Chris Lattner62f254d2005-09-12 22:00:15 +00006861 if (&LI.getParent()->front() != &LI) {
6862 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006863 // If the instruction immediately before this is a store to the same
6864 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00006865 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6866 if (SI->getOperand(1) == LI.getOperand(0))
6867 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006868 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6869 if (LIB->getOperand(0) == LI.getOperand(0))
6870 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00006871 }
Chris Lattner37366c12005-05-01 04:24:53 +00006872
6873 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6874 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6875 isa<UndefValue>(GEPI->getOperand(0))) {
6876 // Insert a new store to null instruction before the load to indicate
6877 // that this code is not reachable. We do this instead of inserting
6878 // an unreachable instruction directly because we cannot modify the
6879 // CFG.
6880 new StoreInst(UndefValue::get(LI.getType()),
6881 Constant::getNullValue(Op->getType()), &LI);
6882 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6883 }
6884
Chris Lattnere87597f2004-10-16 18:11:37 +00006885 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00006886 // load null/undef -> undef
6887 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00006888 // Insert a new store to null instruction before the load to indicate that
6889 // this code is not reachable. We do this instead of inserting an
6890 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00006891 new StoreInst(UndefValue::get(LI.getType()),
6892 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00006893 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00006894 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006895
Chris Lattnere87597f2004-10-16 18:11:37 +00006896 // Instcombine load (constant global) into the value loaded.
6897 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6898 if (GV->isConstant() && !GV->isExternal())
6899 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00006900
Chris Lattnere87597f2004-10-16 18:11:37 +00006901 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6902 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6903 if (CE->getOpcode() == Instruction::GetElementPtr) {
6904 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6905 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00006906 if (Constant *V =
6907 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00006908 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00006909 if (CE->getOperand(0)->isNullValue()) {
6910 // Insert a new store to null instruction before the load to indicate
6911 // that this code is not reachable. We do this instead of inserting
6912 // an unreachable instruction directly because we cannot modify the
6913 // CFG.
6914 new StoreInst(UndefValue::get(LI.getType()),
6915 Constant::getNullValue(Op->getType()), &LI);
6916 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6917 }
6918
Chris Lattnere87597f2004-10-16 18:11:37 +00006919 } else if (CE->getOpcode() == Instruction::Cast) {
6920 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6921 return Res;
6922 }
6923 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00006924
Chris Lattner37366c12005-05-01 04:24:53 +00006925 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006926 // Change select and PHI nodes to select values instead of addresses: this
6927 // helps alias analysis out a lot, allows many others simplifications, and
6928 // exposes redundancy in the code.
6929 //
6930 // Note that we cannot do the transformation unless we know that the
6931 // introduced loads cannot trap! Something like this is valid as long as
6932 // the condition is always false: load (select bool %C, int* null, int* %G),
6933 // but it would not be valid if we transformed it to load from null
6934 // unconditionally.
6935 //
6936 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6937 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00006938 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6939 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006940 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006941 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006942 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006943 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006944 return new SelectInst(SI->getCondition(), V1, V2);
6945 }
6946
Chris Lattner684fe212004-09-23 15:46:00 +00006947 // load (select (cond, null, P)) -> load P
6948 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6949 if (C->isNullValue()) {
6950 LI.setOperand(0, SI->getOperand(2));
6951 return &LI;
6952 }
6953
6954 // load (select (cond, P, null)) -> load P
6955 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6956 if (C->isNullValue()) {
6957 LI.setOperand(0, SI->getOperand(1));
6958 return &LI;
6959 }
6960
Chris Lattnerc10aced2004-09-19 18:43:46 +00006961 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6962 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006963 bool Safe = PN->getParent() == LI.getParent();
6964
6965 // Scan all of the instructions between the PHI and the load to make
6966 // sure there are no instructions that might possibly alter the value
6967 // loaded from the PHI.
6968 if (Safe) {
6969 BasicBlock::iterator I = &LI;
6970 for (--I; !isa<PHINode>(I); --I)
6971 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6972 Safe = false;
6973 break;
6974 }
6975 }
6976
6977 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00006978 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006979 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00006980 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006981
Chris Lattnerc10aced2004-09-19 18:43:46 +00006982 if (Safe) {
6983 // Create the PHI.
6984 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6985 InsertNewInstBefore(NewPN, *PN);
6986 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6987
6988 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6989 BasicBlock *BB = PN->getIncomingBlock(i);
6990 Value *&TheLoad = LoadMap[BB];
6991 if (TheLoad == 0) {
6992 Value *InVal = PN->getIncomingValue(i);
6993 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6994 InVal->getName()+".val"),
6995 *BB->getTerminator());
6996 }
6997 NewPN->addIncoming(TheLoad, BB);
6998 }
6999 return ReplaceInstUsesWith(LI, NewPN);
7000 }
7001 }
7002 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007003 return 0;
7004}
7005
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007006/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7007/// when possible.
7008static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7009 User *CI = cast<User>(SI.getOperand(1));
7010 Value *CastOp = CI->getOperand(0);
7011
7012 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7013 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7014 const Type *SrcPTy = SrcTy->getElementType();
7015
7016 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7017 // If the source is an array, the code below will not succeed. Check to
7018 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7019 // constants.
7020 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7021 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7022 if (ASrcTy->getNumElements() != 0) {
7023 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7024 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7025 SrcTy = cast<PointerType>(CastOp->getType());
7026 SrcPTy = SrcTy->getElementType();
7027 }
7028
7029 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007030 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007031 IC.getTargetData().getTypeSize(DestPTy)) {
7032
7033 // Okay, we are casting from one integer or pointer type to another of
7034 // the same size. Instead of casting the pointer before the store, cast
7035 // the value to be stored.
7036 Value *NewCast;
7037 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7038 NewCast = ConstantExpr::getCast(C, SrcPTy);
7039 else
7040 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7041 SrcPTy,
7042 SI.getOperand(0)->getName()+".c"), SI);
7043
7044 return new StoreInst(NewCast, CastOp);
7045 }
7046 }
7047 }
7048 return 0;
7049}
7050
Chris Lattner2f503e62005-01-31 05:36:43 +00007051Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7052 Value *Val = SI.getOperand(0);
7053 Value *Ptr = SI.getOperand(1);
7054
7055 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00007056 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007057 ++NumCombined;
7058 return 0;
7059 }
7060
Chris Lattner9ca96412006-02-08 03:25:32 +00007061 // Do really simple DSE, to catch cases where there are several consequtive
7062 // stores to the same location, separated by a few arithmetic operations. This
7063 // situation often occurs with bitfield accesses.
7064 BasicBlock::iterator BBI = &SI;
7065 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7066 --ScanInsts) {
7067 --BBI;
7068
7069 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7070 // Prev store isn't volatile, and stores to the same location?
7071 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7072 ++NumDeadStore;
7073 ++BBI;
7074 EraseInstFromFunction(*PrevSI);
7075 continue;
7076 }
7077 break;
7078 }
7079
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007080 // If this is a load, we have to stop. However, if the loaded value is from
7081 // the pointer we're loading and is producing the pointer we're storing,
7082 // then *this* store is dead (X = load P; store X -> P).
7083 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7084 if (LI == Val && LI->getOperand(0) == Ptr) {
7085 EraseInstFromFunction(SI);
7086 ++NumCombined;
7087 return 0;
7088 }
7089 // Otherwise, this is a load from some other location. Stores before it
7090 // may not be dead.
7091 break;
7092 }
7093
Chris Lattner9ca96412006-02-08 03:25:32 +00007094 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007095 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00007096 break;
7097 }
7098
7099
7100 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00007101
7102 // store X, null -> turns into 'unreachable' in SimplifyCFG
7103 if (isa<ConstantPointerNull>(Ptr)) {
7104 if (!isa<UndefValue>(Val)) {
7105 SI.setOperand(0, UndefValue::get(Val->getType()));
7106 if (Instruction *U = dyn_cast<Instruction>(Val))
7107 WorkList.push_back(U); // Dropped a use.
7108 ++NumCombined;
7109 }
7110 return 0; // Do not modify these!
7111 }
7112
7113 // store undef, Ptr -> noop
7114 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00007115 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007116 ++NumCombined;
7117 return 0;
7118 }
7119
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007120 // If the pointer destination is a cast, see if we can fold the cast into the
7121 // source instead.
7122 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7123 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7124 return Res;
7125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7126 if (CE->getOpcode() == Instruction::Cast)
7127 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7128 return Res;
7129
Chris Lattner408902b2005-09-12 23:23:25 +00007130
7131 // If this store is the last instruction in the basic block, and if the block
7132 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00007133 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00007134 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7135 if (BI->isUnconditional()) {
7136 // Check to see if the successor block has exactly two incoming edges. If
7137 // so, see if the other predecessor contains a store to the same location.
7138 // if so, insert a PHI node (if needed) and move the stores down.
7139 BasicBlock *Dest = BI->getSuccessor(0);
7140
7141 pred_iterator PI = pred_begin(Dest);
7142 BasicBlock *Other = 0;
7143 if (*PI != BI->getParent())
7144 Other = *PI;
7145 ++PI;
7146 if (PI != pred_end(Dest)) {
7147 if (*PI != BI->getParent())
7148 if (Other)
7149 Other = 0;
7150 else
7151 Other = *PI;
7152 if (++PI != pred_end(Dest))
7153 Other = 0;
7154 }
7155 if (Other) { // If only one other pred...
7156 BBI = Other->getTerminator();
7157 // Make sure this other block ends in an unconditional branch and that
7158 // there is an instruction before the branch.
7159 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7160 BBI != Other->begin()) {
7161 --BBI;
7162 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7163
7164 // If this instruction is a store to the same location.
7165 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7166 // Okay, we know we can perform this transformation. Insert a PHI
7167 // node now if we need it.
7168 Value *MergedVal = OtherStore->getOperand(0);
7169 if (MergedVal != SI.getOperand(0)) {
7170 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7171 PN->reserveOperandSpace(2);
7172 PN->addIncoming(SI.getOperand(0), SI.getParent());
7173 PN->addIncoming(OtherStore->getOperand(0), Other);
7174 MergedVal = InsertNewInstBefore(PN, Dest->front());
7175 }
7176
7177 // Advance to a place where it is safe to insert the new store and
7178 // insert it.
7179 BBI = Dest->begin();
7180 while (isa<PHINode>(BBI)) ++BBI;
7181 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7182 OtherStore->isVolatile()), *BBI);
7183
7184 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00007185 EraseInstFromFunction(SI);
7186 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00007187 ++NumCombined;
7188 return 0;
7189 }
7190 }
7191 }
7192 }
7193
Chris Lattner2f503e62005-01-31 05:36:43 +00007194 return 0;
7195}
7196
7197
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00007198Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7199 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00007200 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007201 BasicBlock *TrueDest;
7202 BasicBlock *FalseDest;
7203 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7204 !isa<Constant>(X)) {
7205 // Swap Destinations and condition...
7206 BI.setCondition(X);
7207 BI.setSuccessor(0, FalseDest);
7208 BI.setSuccessor(1, TrueDest);
7209 return &BI;
7210 }
7211
7212 // Cannonicalize setne -> seteq
7213 Instruction::BinaryOps Op; Value *Y;
7214 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7215 TrueDest, FalseDest)))
7216 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7217 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7218 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7219 std::string Name = I->getName(); I->setName("");
7220 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7221 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00007222 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007223 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00007224 BI.setSuccessor(0, FalseDest);
7225 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007226 removeFromWorkList(I);
7227 I->getParent()->getInstList().erase(I);
7228 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00007229 return &BI;
7230 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007231
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00007232 return 0;
7233}
Chris Lattner0864acf2002-11-04 16:18:53 +00007234
Chris Lattner46238a62004-07-03 00:26:11 +00007235Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7236 Value *Cond = SI.getCondition();
7237 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7238 if (I->getOpcode() == Instruction::Add)
7239 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7240 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7241 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00007242 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00007243 AddRHS));
7244 SI.setOperand(0, I->getOperand(0));
7245 WorkList.push_back(I);
7246 return &SI;
7247 }
7248 }
7249 return 0;
7250}
7251
Chris Lattner220b0cf2006-03-05 00:22:33 +00007252/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7253/// is to leave as a vector operation.
7254static bool CheapToScalarize(Value *V, bool isConstant) {
7255 if (isa<ConstantAggregateZero>(V))
7256 return true;
7257 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7258 if (isConstant) return true;
7259 // If all elts are the same, we can extract.
7260 Constant *Op0 = C->getOperand(0);
7261 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7262 if (C->getOperand(i) != Op0)
7263 return false;
7264 return true;
7265 }
7266 Instruction *I = dyn_cast<Instruction>(V);
7267 if (!I) return false;
7268
7269 // Insert element gets simplified to the inserted element or is deleted if
7270 // this is constant idx extract element and its a constant idx insertelt.
7271 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7272 isa<ConstantInt>(I->getOperand(2)))
7273 return true;
7274 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7275 return true;
7276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7277 if (BO->hasOneUse() &&
7278 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7279 CheapToScalarize(BO->getOperand(1), isConstant)))
7280 return true;
7281
7282 return false;
7283}
7284
Chris Lattner863bcff2006-05-25 23:48:38 +00007285/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7286/// elements into values that are larger than the #elts in the input.
7287static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7288 unsigned NElts = SVI->getType()->getNumElements();
7289 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7290 return std::vector<unsigned>(NElts, 0);
7291 if (isa<UndefValue>(SVI->getOperand(2)))
7292 return std::vector<unsigned>(NElts, 2*NElts);
7293
7294 std::vector<unsigned> Result;
7295 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7296 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7297 if (isa<UndefValue>(CP->getOperand(i)))
7298 Result.push_back(NElts*2); // undef -> 8
7299 else
7300 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7301 return Result;
7302}
7303
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007304/// FindScalarElement - Given a vector and an element number, see if the scalar
7305/// value is already around as a register, for example if it were inserted then
7306/// extracted from the vector.
7307static Value *FindScalarElement(Value *V, unsigned EltNo) {
7308 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7309 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00007310 unsigned Width = PTy->getNumElements();
7311 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007312 return UndefValue::get(PTy->getElementType());
7313
7314 if (isa<UndefValue>(V))
7315 return UndefValue::get(PTy->getElementType());
7316 else if (isa<ConstantAggregateZero>(V))
7317 return Constant::getNullValue(PTy->getElementType());
7318 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7319 return CP->getOperand(EltNo);
7320 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7321 // If this is an insert to a variable element, we don't know what it is.
7322 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7323 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7324
7325 // If this is an insert to the element we are looking for, return the
7326 // inserted value.
7327 if (EltNo == IIElt) return III->getOperand(1);
7328
7329 // Otherwise, the insertelement doesn't modify the value, recurse on its
7330 // vector input.
7331 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00007332 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00007333 unsigned InEl = getShuffleMask(SVI)[EltNo];
7334 if (InEl < Width)
7335 return FindScalarElement(SVI->getOperand(0), InEl);
7336 else if (InEl < Width*2)
7337 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7338 else
7339 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007340 }
7341
7342 // Otherwise, we don't know.
7343 return 0;
7344}
7345
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007346Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007347
Chris Lattner1f13c882006-03-31 18:25:14 +00007348 // If packed val is undef, replace extract with scalar undef.
7349 if (isa<UndefValue>(EI.getOperand(0)))
7350 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7351
7352 // If packed val is constant 0, replace extract with scalar 0.
7353 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7354 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7355
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007356 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7357 // If packed val is constant with uniform operands, replace EI
7358 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00007359 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007360 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00007361 if (C->getOperand(i) != op0) {
7362 op0 = 0;
7363 break;
7364 }
7365 if (op0)
7366 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007367 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00007368
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007369 // If extracting a specified index from the vector, see if we can recursively
7370 // find a previously computed scalar that was inserted into the vector.
Chris Lattner389a6f52006-04-10 23:06:36 +00007371 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007372 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7373 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00007374 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007375
Chris Lattner73fa49d2006-05-25 22:53:38 +00007376 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007377 if (I->hasOneUse()) {
7378 // Push extractelement into predecessor operation if legal and
7379 // profitable to do so
7380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00007381 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7382 if (CheapToScalarize(BO, isConstantElt)) {
7383 ExtractElementInst *newEI0 =
7384 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7385 EI.getName()+".lhs");
7386 ExtractElementInst *newEI1 =
7387 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7388 EI.getName()+".rhs");
7389 InsertNewInstBefore(newEI0, EI);
7390 InsertNewInstBefore(newEI1, EI);
7391 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7392 }
7393 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007394 Value *Ptr = InsertCastBefore(I->getOperand(0),
7395 PointerType::get(EI.getType()), EI);
7396 GetElementPtrInst *GEP =
7397 new GetElementPtrInst(Ptr, EI.getOperand(1),
7398 I->getName() + ".gep");
7399 InsertNewInstBefore(GEP, EI);
7400 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00007401 }
7402 }
7403 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7404 // Extracting the inserted element?
7405 if (IE->getOperand(2) == EI.getOperand(1))
7406 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7407 // If the inserted and extracted elements are constants, they must not
7408 // be the same value, extract from the pre-inserted value instead.
7409 if (isa<Constant>(IE->getOperand(2)) &&
7410 isa<Constant>(EI.getOperand(1))) {
7411 AddUsesToWorkList(EI);
7412 EI.setOperand(0, IE->getOperand(0));
7413 return &EI;
7414 }
7415 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7416 // If this is extracting an element from a shufflevector, figure out where
7417 // it came from and extract from the appropriate input element instead.
7418 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner863bcff2006-05-25 23:48:38 +00007419 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7420 Value *Src;
7421 if (SrcIdx < SVI->getType()->getNumElements())
7422 Src = SVI->getOperand(0);
7423 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7424 SrcIdx -= SVI->getType()->getNumElements();
7425 Src = SVI->getOperand(1);
7426 } else {
7427 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00007428 }
Chris Lattner863bcff2006-05-25 23:48:38 +00007429 return new ExtractElementInst(Src,
7430 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007431 }
7432 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00007433 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007434 return 0;
7435}
7436
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007437/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7438/// elements from either LHS or RHS, return the shuffle mask and true.
7439/// Otherwise, return false.
7440static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7441 std::vector<Constant*> &Mask) {
7442 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7443 "Invalid CollectSingleShuffleElements");
7444 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7445
7446 if (isa<UndefValue>(V)) {
7447 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7448 return true;
7449 } else if (V == LHS) {
7450 for (unsigned i = 0; i != NumElts; ++i)
7451 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7452 return true;
7453 } else if (V == RHS) {
7454 for (unsigned i = 0; i != NumElts; ++i)
7455 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7456 return true;
7457 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7458 // If this is an insert of an extract from some other vector, include it.
7459 Value *VecOp = IEI->getOperand(0);
7460 Value *ScalarOp = IEI->getOperand(1);
7461 Value *IdxOp = IEI->getOperand(2);
7462
Chris Lattnerd929f062006-04-27 21:14:21 +00007463 if (!isa<ConstantInt>(IdxOp))
7464 return false;
7465 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7466
7467 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7468 // Okay, we can handle this if the vector we are insertinting into is
7469 // transitively ok.
7470 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7471 // If so, update the mask to reflect the inserted undef.
7472 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7473 return true;
7474 }
7475 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7476 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007477 EI->getOperand(0)->getType() == V->getType()) {
7478 unsigned ExtractedIdx =
7479 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007480
7481 // This must be extracting from either LHS or RHS.
7482 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7483 // Okay, we can handle this if the vector we are insertinting into is
7484 // transitively ok.
7485 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7486 // If so, update the mask to reflect the inserted value.
7487 if (EI->getOperand(0) == LHS) {
7488 Mask[InsertedIdx & (NumElts-1)] =
7489 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7490 } else {
7491 assert(EI->getOperand(0) == RHS);
7492 Mask[InsertedIdx & (NumElts-1)] =
7493 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7494
7495 }
7496 return true;
7497 }
7498 }
7499 }
7500 }
7501 }
7502 // TODO: Handle shufflevector here!
7503
7504 return false;
7505}
7506
7507/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7508/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7509/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00007510static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007511 Value *&RHS) {
7512 assert(isa<PackedType>(V->getType()) &&
7513 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00007514 "Invalid shuffle!");
7515 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7516
7517 if (isa<UndefValue>(V)) {
7518 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7519 return V;
7520 } else if (isa<ConstantAggregateZero>(V)) {
7521 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7522 return V;
7523 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7524 // If this is an insert of an extract from some other vector, include it.
7525 Value *VecOp = IEI->getOperand(0);
7526 Value *ScalarOp = IEI->getOperand(1);
7527 Value *IdxOp = IEI->getOperand(2);
7528
7529 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7530 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7531 EI->getOperand(0)->getType() == V->getType()) {
7532 unsigned ExtractedIdx =
7533 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7534 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7535
7536 // Either the extracted from or inserted into vector must be RHSVec,
7537 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007538 if (EI->getOperand(0) == RHS || RHS == 0) {
7539 RHS = EI->getOperand(0);
7540 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007541 Mask[InsertedIdx & (NumElts-1)] =
7542 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7543 return V;
7544 }
7545
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007546 if (VecOp == RHS) {
7547 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007548 // Everything but the extracted element is replaced with the RHS.
7549 for (unsigned i = 0; i != NumElts; ++i) {
7550 if (i != InsertedIdx)
7551 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7552 }
7553 return V;
7554 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007555
7556 // If this insertelement is a chain that comes from exactly these two
7557 // vectors, return the vector and the effective shuffle.
7558 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7559 return EI->getOperand(0);
7560
Chris Lattnerefb47352006-04-15 01:39:45 +00007561 }
7562 }
7563 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007564 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00007565
7566 // Otherwise, can't do anything fancy. Return an identity vector.
7567 for (unsigned i = 0; i != NumElts; ++i)
7568 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7569 return V;
7570}
7571
7572Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7573 Value *VecOp = IE.getOperand(0);
7574 Value *ScalarOp = IE.getOperand(1);
7575 Value *IdxOp = IE.getOperand(2);
7576
7577 // If the inserted element was extracted from some other vector, and if the
7578 // indexes are constant, try to turn this into a shufflevector operation.
7579 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7580 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7581 EI->getOperand(0)->getType() == IE.getType()) {
7582 unsigned NumVectorElts = IE.getType()->getNumElements();
7583 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7584 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7585
7586 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7587 return ReplaceInstUsesWith(IE, VecOp);
7588
7589 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7590 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7591
7592 // If we are extracting a value from a vector, then inserting it right
7593 // back into the same place, just use the input vector.
7594 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7595 return ReplaceInstUsesWith(IE, VecOp);
7596
7597 // We could theoretically do this for ANY input. However, doing so could
7598 // turn chains of insertelement instructions into a chain of shufflevector
7599 // instructions, and right now we do not merge shufflevectors. As such,
7600 // only do this in a situation where it is clear that there is benefit.
7601 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7602 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7603 // the values of VecOp, except then one read from EIOp0.
7604 // Build a new shuffle mask.
7605 std::vector<Constant*> Mask;
7606 if (isa<UndefValue>(VecOp))
7607 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7608 else {
7609 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7610 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7611 NumVectorElts));
7612 }
7613 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7614 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7615 ConstantPacked::get(Mask));
7616 }
7617
7618 // If this insertelement isn't used by some other insertelement, turn it
7619 // (and any insertelements it points to), into one big shuffle.
7620 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7621 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007622 Value *RHS = 0;
7623 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7624 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7625 // We now have a shuffle of LHS, RHS, Mask.
7626 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00007627 }
7628 }
7629 }
7630
7631 return 0;
7632}
7633
7634
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007635Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7636 Value *LHS = SVI.getOperand(0);
7637 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00007638 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007639
7640 bool MadeChange = false;
7641
Chris Lattner863bcff2006-05-25 23:48:38 +00007642 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007643 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7644
Chris Lattnerefb47352006-04-15 01:39:45 +00007645 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7646 // the undef, change them to undefs.
7647
Chris Lattner863bcff2006-05-25 23:48:38 +00007648 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7649 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7650 if (LHS == RHS || isa<UndefValue>(LHS)) {
7651 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007652 // shuffle(undef,undef,mask) -> undef.
7653 return ReplaceInstUsesWith(SVI, LHS);
7654 }
7655
Chris Lattner863bcff2006-05-25 23:48:38 +00007656 // Remap any references to RHS to use LHS.
7657 std::vector<Constant*> Elts;
7658 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00007659 if (Mask[i] >= 2*e)
Chris Lattner863bcff2006-05-25 23:48:38 +00007660 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner7b2e27922006-05-26 00:29:06 +00007661 else {
7662 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7663 (Mask[i] < e && isa<UndefValue>(LHS)))
7664 Mask[i] = 2*e; // Turn into undef.
7665 else
7666 Mask[i] &= (e-1); // Force to LHS.
7667 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7668 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007669 }
Chris Lattner863bcff2006-05-25 23:48:38 +00007670 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007671 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner863bcff2006-05-25 23:48:38 +00007672 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00007673 LHS = SVI.getOperand(0);
7674 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007675 MadeChange = true;
7676 }
7677
Chris Lattner7b2e27922006-05-26 00:29:06 +00007678 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00007679 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00007680
Chris Lattner863bcff2006-05-25 23:48:38 +00007681 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7682 if (Mask[i] >= e*2) continue; // Ignore undef values.
7683 // Is this an identity shuffle of the LHS value?
7684 isLHSID &= (Mask[i] == i);
7685
7686 // Is this an identity shuffle of the RHS value?
7687 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00007688 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007689
Chris Lattner863bcff2006-05-25 23:48:38 +00007690 // Eliminate identity shuffles.
7691 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7692 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007693
Chris Lattner7b2e27922006-05-26 00:29:06 +00007694 // If the LHS is a shufflevector itself, see if we can combine it with this
7695 // one without producing an unusual shuffle. Here we are really conservative:
7696 // we are absolutely afraid of producing a shuffle mask not in the input
7697 // program, because the code gen may not be smart enough to turn a merged
7698 // shuffle into two specific shuffles: it may produce worse code. As such,
7699 // we only merge two shuffles if the result is one of the two input shuffle
7700 // masks. In this case, merging the shuffles just removes one instruction,
7701 // which we know is safe. This is good for things like turning:
7702 // (splat(splat)) -> splat.
7703 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7704 if (isa<UndefValue>(RHS)) {
7705 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7706
7707 std::vector<unsigned> NewMask;
7708 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7709 if (Mask[i] >= 2*e)
7710 NewMask.push_back(2*e);
7711 else
7712 NewMask.push_back(LHSMask[Mask[i]]);
7713
7714 // If the result mask is equal to the src shuffle or this shuffle mask, do
7715 // the replacement.
7716 if (NewMask == LHSMask || NewMask == Mask) {
7717 std::vector<Constant*> Elts;
7718 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7719 if (NewMask[i] >= e*2) {
7720 Elts.push_back(UndefValue::get(Type::UIntTy));
7721 } else {
7722 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7723 }
7724 }
7725 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7726 LHSSVI->getOperand(1),
7727 ConstantPacked::get(Elts));
7728 }
7729 }
7730 }
7731
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007732 return MadeChange ? &SVI : 0;
7733}
7734
7735
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007736
Chris Lattner62b14df2002-09-02 04:59:56 +00007737void InstCombiner::removeFromWorkList(Instruction *I) {
7738 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7739 WorkList.end());
7740}
7741
Chris Lattnerea1c4542004-12-08 23:43:58 +00007742
7743/// TryToSinkInstruction - Try to move the specified instruction from its
7744/// current block into the beginning of DestBlock, which can only happen if it's
7745/// safe to move the instruction past all of the instructions between it and the
7746/// end of its block.
7747static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7748 assert(I->hasOneUse() && "Invariants didn't hold!");
7749
Chris Lattner108e9022005-10-27 17:13:11 +00007750 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7751 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00007752
Chris Lattnerea1c4542004-12-08 23:43:58 +00007753 // Do not sink alloca instructions out of the entry block.
7754 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7755 return false;
7756
Chris Lattner96a52a62004-12-09 07:14:34 +00007757 // We can only sink load instructions if there is nothing between the load and
7758 // the end of block that could change the value.
7759 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00007760 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7761 Scan != E; ++Scan)
7762 if (Scan->mayWriteToMemory())
7763 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00007764 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00007765
7766 BasicBlock::iterator InsertPos = DestBlock->begin();
7767 while (isa<PHINode>(InsertPos)) ++InsertPos;
7768
Chris Lattner4bc5f802005-08-08 19:11:57 +00007769 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00007770 ++NumSunkInst;
7771 return true;
7772}
7773
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007774/// OptimizeConstantExpr - Given a constant expression and target data layout
7775/// information, symbolically evaluation the constant expr to something simpler
7776/// if possible.
7777static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7778 if (!TD) return CE;
7779
7780 Constant *Ptr = CE->getOperand(0);
7781 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7782 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7783 // If this is a constant expr gep that is effectively computing an
7784 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7785 bool isFoldableGEP = true;
7786 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7787 if (!isa<ConstantInt>(CE->getOperand(i)))
7788 isFoldableGEP = false;
7789 if (isFoldableGEP) {
7790 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7791 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7792 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7793 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7794 return ConstantExpr::getCast(C, CE->getType());
7795 }
7796 }
7797
7798 return CE;
7799}
7800
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007801
7802/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7803/// all reachable code to the worklist.
7804///
7805/// This has a couple of tricks to make the code faster and more powerful. In
7806/// particular, we constant fold and DCE instructions as we go, to avoid adding
7807/// them to the worklist (this significantly speeds up instcombine on code where
7808/// many instructions are dead or constant). Additionally, if we find a branch
7809/// whose condition is a known constant, we only visit the reachable successors.
7810///
7811static void AddReachableCodeToWorklist(BasicBlock *BB,
7812 std::set<BasicBlock*> &Visited,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007813 std::vector<Instruction*> &WorkList,
7814 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007815 // We have now visited this block! If we've already been here, bail out.
7816 if (!Visited.insert(BB).second) return;
7817
7818 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7819 Instruction *Inst = BBI++;
7820
7821 // DCE instruction if trivially dead.
7822 if (isInstructionTriviallyDead(Inst)) {
7823 ++NumDeadInst;
7824 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7825 Inst->eraseFromParent();
7826 continue;
7827 }
7828
7829 // ConstantProp instruction if trivially constant.
7830 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007831 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7832 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007833 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7834 Inst->replaceAllUsesWith(C);
7835 ++NumConstProp;
7836 Inst->eraseFromParent();
7837 continue;
7838 }
7839
7840 WorkList.push_back(Inst);
7841 }
7842
7843 // Recursively visit successors. If this is a branch or switch on a constant,
7844 // only visit the reachable successor.
7845 TerminatorInst *TI = BB->getTerminator();
7846 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7847 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7848 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007849 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7850 TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007851 return;
7852 }
7853 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7854 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7855 // See if this is an explicit destination.
7856 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7857 if (SI->getCaseValue(i) == Cond) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007858 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007859 return;
7860 }
7861
7862 // Otherwise it is the default destination.
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007863 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007864 return;
7865 }
7866 }
7867
7868 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007869 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007870}
7871
Chris Lattner7e708292002-06-25 16:13:24 +00007872bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007873 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00007874 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00007875
Chris Lattnerb3d59702005-07-07 20:40:38 +00007876 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007877 // Do a depth-first traversal of the function, populate the worklist with
7878 // the reachable instructions. Ignore blocks that are not reachable. Keep
7879 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00007880 std::set<BasicBlock*> Visited;
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007881 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00007882
Chris Lattnerb3d59702005-07-07 20:40:38 +00007883 // Do a quick scan over the function. If we find any blocks that are
7884 // unreachable, remove any instructions inside of them. This prevents
7885 // the instcombine code from having to deal with some bad special cases.
7886 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7887 if (!Visited.count(BB)) {
7888 Instruction *Term = BB->getTerminator();
7889 while (Term != BB->begin()) { // Remove instrs bottom-up
7890 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00007891
Chris Lattnerb3d59702005-07-07 20:40:38 +00007892 DEBUG(std::cerr << "IC: DCE: " << *I);
7893 ++NumDeadInst;
7894
7895 if (!I->use_empty())
7896 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7897 I->eraseFromParent();
7898 }
7899 }
7900 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007901
7902 while (!WorkList.empty()) {
7903 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7904 WorkList.pop_back();
7905
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007906 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00007907 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007908 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00007909 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007910 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00007911 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00007912
Chris Lattnerad5fec12005-01-28 19:32:01 +00007913 DEBUG(std::cerr << "IC: DCE: " << *I);
7914
7915 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00007916 removeFromWorkList(I);
7917 continue;
7918 }
Chris Lattner62b14df2002-09-02 04:59:56 +00007919
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007920 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner62b14df2002-09-02 04:59:56 +00007921 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007922 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7923 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerad5fec12005-01-28 19:32:01 +00007924 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7925
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007926 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007927 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00007928 ReplaceInstUsesWith(*I, C);
7929
Chris Lattner62b14df2002-09-02 04:59:56 +00007930 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007931 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00007932 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007933 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00007934 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00007935
Chris Lattnerea1c4542004-12-08 23:43:58 +00007936 // See if we can trivially sink this instruction to a successor basic block.
7937 if (I->hasOneUse()) {
7938 BasicBlock *BB = I->getParent();
7939 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7940 if (UserParent != BB) {
7941 bool UserIsSuccessor = false;
7942 // See if the user is one of our successors.
7943 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7944 if (*SI == UserParent) {
7945 UserIsSuccessor = true;
7946 break;
7947 }
7948
7949 // If the user is one of our immediate successors, and if that successor
7950 // only has us as a predecessors (we'd have to split the critical edge
7951 // otherwise), we can keep going.
7952 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7953 next(pred_begin(UserParent)) == pred_end(UserParent))
7954 // Okay, the CFG is simple enough, try to sink this instruction.
7955 Changed |= TryToSinkInstruction(I, UserParent);
7956 }
7957 }
7958
Chris Lattner8a2a3112001-12-14 16:52:21 +00007959 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00007960 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00007961 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007962 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007963 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007964 DEBUG(std::cerr << "IC: Old = " << *I
7965 << " New = " << *Result);
7966
Chris Lattnerf523d062004-06-09 05:08:07 +00007967 // Everything uses the new instruction now.
7968 I->replaceAllUsesWith(Result);
7969
7970 // Push the new instruction and any users onto the worklist.
7971 WorkList.push_back(Result);
7972 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007973
7974 // Move the name to the new instruction first...
7975 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00007976 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007977
7978 // Insert the new instruction into the basic block...
7979 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00007980 BasicBlock::iterator InsertPos = I;
7981
7982 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7983 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7984 ++InsertPos;
7985
7986 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007987
Chris Lattner00d51312004-05-01 23:27:23 +00007988 // Make sure that we reprocess all operands now that we reduced their
7989 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00007990 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7991 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7992 WorkList.push_back(OpI);
7993
Chris Lattnerf523d062004-06-09 05:08:07 +00007994 // Instructions can end up on the worklist more than once. Make sure
7995 // we do not process an instruction that has been deleted.
7996 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007997
7998 // Erase the old instruction.
7999 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00008000 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00008001 DEBUG(std::cerr << "IC: MOD = " << *I);
8002
Chris Lattner90ac28c2002-08-02 19:29:35 +00008003 // If the instruction was modified, it's possible that it is now dead.
8004 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00008005 if (isInstructionTriviallyDead(I)) {
8006 // Make sure we process all operands now that we are reducing their
8007 // use counts.
8008 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8009 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8010 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008011
Chris Lattner00d51312004-05-01 23:27:23 +00008012 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008013 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008014 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00008015 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00008016 } else {
8017 WorkList.push_back(Result);
8018 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00008019 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008020 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008021 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008022 }
8023 }
8024
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008025 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008026}
8027
Brian Gaeke96d4bf72004-07-27 17:43:21 +00008028FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008029 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008030}
Brian Gaeked0fde302003-11-11 22:41:34 +00008031