blob: 798e3d24e9f0b3301c0b31db8d0d791cc99c16aa [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp 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"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000059#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000060#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000061#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000063#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000064#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000065#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000066#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000077 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000080 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000083 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000084 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000086 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000088
Owen Andersone922c022009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000091
Chris Lattnerdbab3862007-03-02 21:28:56 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000122 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126 }
127
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000134 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000135 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif177dd3f2008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000148 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 // Set the operand to undef to drop the use.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000151 }
152
153 return R;
154 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000155
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000157 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000158
159 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160
Chris Lattner97e52e42002-04-28 21:27:06 +0000161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000162 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000163 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000164 }
165
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000167
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000172 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000173 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000174 //
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000215
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000217 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000219 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000222 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000234 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000244 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000245 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000246 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000247 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000248 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000249 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000250 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000256 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000257
Chris Lattner9fe38862003-06-19 17:00:31 +0000258 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000259 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000260 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Chris Lattner9fe38862003-06-19 17:00:31 +0000267
Chris Lattner28977af2004-04-05 01:30:19 +0000268 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
Chris Lattner955f3312004-09-28 21:48:02 +0000272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000277 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000278 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000279 }
280
Chris Lattner0c967662004-09-24 15:21:34 +0000281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000286 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattnere2ed0572006-04-06 19:19:17 +0000288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000290
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000292 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000293 return C;
294 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Chris Lattner0c967662004-09-24 15:21:34 +0000300
Chris Lattner8b170942002-08-09 23:47:40 +0000301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000316 return &I;
317 }
Chris Lattner8b170942002-08-09 23:47:40 +0000318 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319
320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000327 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000328 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000329 return 0; // Don't do anything with FI
330 }
Chris Lattner173234a2008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000345 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000349 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000350
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner886ab6c2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng388df622009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000371
Chris Lattner4e998b22004-09-29 05:07:12 +0000372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
Chris Lattnerbac32862004-11-14 19:13:23 +0000377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Chris Lattner7da52b22006-11-01 04:51:18 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000387
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000389 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000391 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000397
Chris Lattnerafe91a52006-06-15 19:07:26 +0000398
Reid Spencerc55b2432006-12-13 18:21:21 +0000399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400
Dan Gohman6de29f82009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000405
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000406 };
407}
408
Dan Gohman844731a2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Chris Lattner4f98c562003-03-10 21:43:22 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000415static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 return 3;
421 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000425}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000426
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000430 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000431}
432
Chris Lattner4cb170c2004-02-23 06:38:22 +0000433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000439 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000440 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000441}
442
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 }
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return 0;
455}
456
Reid Spencer3da59db2006-11-27 01:05:10 +0000457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Chris Lattnera0e69692009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000475 DstTy,
476 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 Res = 0;
483
484 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000485}
486
487/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488/// in any code being generated. It does not require codegen if V is simple
489/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
Chris Lattner01575b72006-05-25 23:24:33 +0000494 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000497 return false;
498 return true;
499}
500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000503//
Chris Lattner4f98c562003-03-10 21:43:22 +0000504// 1. Order operands such that they are listed from right (least complex) to
505// left (most complex). This puts constants before unary operators before
506// binary operators.
507//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000510//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000513 if (getComplexity(Context, I.getOperand(0)) <
514 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000516
Chris Lattner4f98c562003-03-10 21:43:22 +0000517 if (!I.isAssociative()) return Changed;
518 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000522 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000523 cast<Constant>(I.getOperand(1)),
524 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 I.setOperand(0, Op->getOperand(0));
526 I.setOperand(1, Folded);
527 return true;
528 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530 isOnlyUse(Op) && isOnlyUse(Op1)) {
531 Constant *C1 = cast<Constant>(Op->getOperand(1));
532 Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000535 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000536 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 Op1->getOperand(0),
538 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000539 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000540 I.setOperand(0, New);
541 I.setOperand(1, Folded);
542 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000543 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000546}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000547
Reid Spencere4d87aa2006-12-23 06:05:41 +0000548/// SimplifyCompare - For a CmpInst this function just orders the operands
549/// so that theyare listed from right (least complex) to left (most complex).
550/// This puts constants before unary operators before binary operators.
551bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000552 if (getComplexity(Context, I.getOperand(0)) >=
553 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
Chris Lattner8d969642003-03-10 23:06:50 +0000560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000562//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000563static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000565 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000566
Chris Lattner0ce85802004-12-14 20:08:06 +0000567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000574
Chris Lattner8d969642003-03-10 23:06:50 +0000575 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000576}
577
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000582static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Owen Anderson07cf79e2009-07-06 23:00:19 +0000597static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000598 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000599 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000600
601 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000602 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersoneed707b2009-07-24 23:12:02 +0000603 return ConstantInt::get(*Context, ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000604 return 0;
605}
606
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607// dyn_castFoldableMul - If this value is a multiply that can be folded into
608// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000609// non-constant operand of the multiply, and set CST to point to the multiplier.
610// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000611//
Owen Andersond672ecb2009-07-03 00:17:18 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000613 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000614 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000615 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000617 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000618 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000619 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000620 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000621 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000622 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000623 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +0000624 CST = ConstantInt::get(*Context, APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 return I->getOperand(0);
626 }
627 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000629}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000630
Reid Spencer7177c3a2007-03-25 05:33:51 +0000631/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000632static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000635}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000636/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000637static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000644 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000645 uint32_t W = C1->getBitWidth();
646 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
647 if (sign) {
648 LHSExt.sext(W * 2);
649 RHSExt.sext(W * 2);
650 } else {
651 LHSExt.zext(W * 2);
652 RHSExt.zext(W * 2);
653 }
654
655 APInt MulExt = LHSExt * RHSExt;
656
657 if (sign) {
658 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
659 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
660 return MulExt.slt(Min) || MulExt.sgt(Max);
661 } else
662 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
663}
Chris Lattner955f3312004-09-28 21:48:02 +0000664
Reid Spencere7816b52007-03-08 01:52:58 +0000665
Chris Lattner255d8912006-02-11 09:31:47 +0000666/// ShrinkDemandedConstant - Check to see if the specified operand of the
667/// specified instruction is a constant integer. If so, check to see if there
668/// are any bits set in the constant that are not demanded. If so, shrink the
669/// constant and return true.
670static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000671 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000672 assert(I && "No instruction?");
673 assert(OpNo < I->getNumOperands() && "Operand index too large");
674
675 // If the operand is not a constant integer, nothing to do.
676 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
677 if (!OpC) return false;
678
679 // If there are no bits set that aren't demanded, nothing to do.
680 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
681 if ((~Demanded & OpC->getValue()) == 0)
682 return false;
683
684 // This instruction is producing bits that are not demanded. Shrink the RHS.
685 Demanded &= OpC->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +0000686 I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000687 return true;
688}
689
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000690// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
691// set of known zero and one bits, compute the maximum and minimum values that
692// could have the specified known zero and known one bits, returning them in
693// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000694static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000695 const APInt& KnownOne,
696 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000697 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
698 KnownZero.getBitWidth() == Min.getBitWidth() &&
699 KnownZero.getBitWidth() == Max.getBitWidth() &&
700 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000701 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000702
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000703 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
704 // bit if it is unknown.
705 Min = KnownOne;
706 Max = KnownOne|UnknownBits;
707
Dan Gohman1c8491e2009-04-25 17:12:48 +0000708 if (UnknownBits.isNegative()) { // Sign bit is unknown
709 Min.set(Min.getBitWidth()-1);
710 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712}
713
714// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
715// a set of known zero and one bits, compute the maximum and minimum values that
716// could have the specified known zero and known one bits, returning them in
717// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000718static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000719 const APInt &KnownOne,
720 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000721 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
722 KnownZero.getBitWidth() == Min.getBitWidth() &&
723 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000724 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000725 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726
727 // The minimum value is when the unknown bits are all zeros.
728 Min = KnownOne;
729 // The maximum value is when the unknown bits are all ones.
730 Max = KnownOne|UnknownBits;
731}
Chris Lattner255d8912006-02-11 09:31:47 +0000732
Chris Lattner886ab6c2009-01-31 08:15:18 +0000733/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
734/// SimplifyDemandedBits knows about. See if the instruction has any
735/// properties that allow us to simplify its operands.
736bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000737 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000738 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
739 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
740
741 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
742 KnownZero, KnownOne, 0);
743 if (V == 0) return false;
744 if (V == &Inst) return true;
745 ReplaceInstUsesWith(Inst, V);
746 return true;
747}
748
749/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
750/// specified instruction operand if possible, updating it in place. It returns
751/// true if it made any change and false otherwise.
752bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
753 APInt &KnownZero, APInt &KnownOne,
754 unsigned Depth) {
755 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
756 KnownZero, KnownOne, Depth);
757 if (NewVal == 0) return false;
758 U.set(NewVal);
759 return true;
760}
761
762
763/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
764/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000765/// that only the bits set in DemandedMask of the result of V are ever used
766/// downstream. Consequently, depending on the mask and V, it may be possible
767/// to replace V with a constant or one of its operands. In such cases, this
768/// function does the replacement and returns true. In all other cases, it
769/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000770/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000771/// to be zero in the expression. These are provided to potentially allow the
772/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773/// the expression. KnownOne and KnownZero always follow the invariant that
774/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775/// the bits in KnownOne and KnownZero may only be accurate for those bits set
776/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000778///
779/// This returns null if it did not change anything and it permits no
780/// simplification. This returns V itself if it did some simplification of V's
781/// operands based on the information about what bits are demanded. This returns
782/// some other non-null value if it found out that V is equal to another value
783/// in the context where the specified bits are demanded, but not for all users.
784Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
785 APInt &KnownZero, APInt &KnownOne,
786 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000787 assert(V != 0 && "Null pointer of Value???");
788 assert(Depth <= 6 && "Limit Search Depth");
789 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000790 const Type *VTy = V->getType();
791 assert((TD || !isa<PointerType>(VTy)) &&
792 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000793 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
794 (!VTy->isIntOrIntVector() ||
795 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000796 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000797 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000798 "Value *V, DemandedMask, KnownZero and KnownOne "
799 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000800 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
801 // We know all of the bits for a constant!
802 KnownOne = CI->getValue() & DemandedMask;
803 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000804 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000805 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000806 if (isa<ConstantPointerNull>(V)) {
807 // We know all of the bits for a constant!
808 KnownOne.clear();
809 KnownZero = DemandedMask;
810 return 0;
811 }
812
Chris Lattner08d2cc72009-01-31 07:26:06 +0000813 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000814 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000815 if (DemandedMask == 0) { // Not demanding any bits from V.
816 if (isa<UndefValue>(V))
817 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000818 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000819 }
820
Chris Lattner4598c942009-01-31 08:24:16 +0000821 if (Depth == 6) // Limit search depth.
822 return 0;
823
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000824 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
825 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
826
Dan Gohman1c8491e2009-04-25 17:12:48 +0000827 Instruction *I = dyn_cast<Instruction>(V);
828 if (!I) {
829 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
830 return 0; // Only analyze instructions.
831 }
832
Chris Lattner4598c942009-01-31 08:24:16 +0000833 // If there are multiple uses of this value and we aren't at the root, then
834 // we can't do any simplifications of the operands, because DemandedMask
835 // only reflects the bits demanded by *one* of the users.
836 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000837 // Despite the fact that we can't simplify this instruction in all User's
838 // context, we can at least compute the knownzero/knownone bits, and we can
839 // do simplifications that apply to *just* the one user if we know that
840 // this instruction has a simpler value in that context.
841 if (I->getOpcode() == Instruction::And) {
842 // If either the LHS or the RHS are Zero, the result is zero.
843 ComputeMaskedBits(I->getOperand(1), DemandedMask,
844 RHSKnownZero, RHSKnownOne, Depth+1);
845 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
846 LHSKnownZero, LHSKnownOne, Depth+1);
847
848 // If all of the demanded bits are known 1 on one side, return the other.
849 // These bits cannot contribute to the result of the 'and' in this
850 // context.
851 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
852 (DemandedMask & ~LHSKnownZero))
853 return I->getOperand(0);
854 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
855 (DemandedMask & ~RHSKnownZero))
856 return I->getOperand(1);
857
858 // If all of the demanded bits in the inputs are known zeros, return zero.
859 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000860 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000861
862 } else if (I->getOpcode() == Instruction::Or) {
863 // We can simplify (X|Y) -> X or Y in the user's context if we know that
864 // only bits from X or Y are demanded.
865
866 // If either the LHS or the RHS are One, the result is One.
867 ComputeMaskedBits(I->getOperand(1), DemandedMask,
868 RHSKnownZero, RHSKnownOne, Depth+1);
869 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
870 LHSKnownZero, LHSKnownOne, Depth+1);
871
872 // If all of the demanded bits are known zero on one side, return the
873 // other. These bits cannot contribute to the result of the 'or' in this
874 // context.
875 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
876 (DemandedMask & ~LHSKnownOne))
877 return I->getOperand(0);
878 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
879 (DemandedMask & ~RHSKnownOne))
880 return I->getOperand(1);
881
882 // If all of the potentially set bits on one side are known to be set on
883 // the other side, just use the 'other' side.
884 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
885 (DemandedMask & (~RHSKnownZero)))
886 return I->getOperand(0);
887 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
888 (DemandedMask & (~LHSKnownZero)))
889 return I->getOperand(1);
890 }
891
Chris Lattner4598c942009-01-31 08:24:16 +0000892 // Compute the KnownZero/KnownOne bits to simplify things downstream.
893 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
894 return 0;
895 }
896
897 // If this is the root being simplified, allow it to have multiple uses,
898 // just set the DemandedMask to all bits so that we can try to simplify the
899 // operands. This allows visitTruncInst (for example) to simplify the
900 // operand of a trunc without duplicating all the logic below.
901 if (Depth == 0 && !V->hasOneUse())
902 DemandedMask = APInt::getAllOnesValue(BitWidth);
903
Reid Spencer8cb68342007-03-12 17:25:59 +0000904 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000905 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000906 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000907 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000908 case Instruction::And:
909 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000910 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
911 RHSKnownZero, RHSKnownOne, Depth+1) ||
912 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000913 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000914 return I;
915 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
916 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000917
918 // If all of the demanded bits are known 1 on one side, return the other.
919 // These bits cannot contribute to the result of the 'and'.
920 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
921 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
924 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000925 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000926
927 // If all of the demanded bits in the inputs are known zeros, return zero.
928 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000929 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000930
931 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000932 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // Output known-1 bits are only known if set in both the LHS & RHS.
936 RHSKnownOne &= LHSKnownOne;
937 // Output known-0 are known to be clear if zero in either the LHS | RHS.
938 RHSKnownZero |= LHSKnownZero;
939 break;
940 case Instruction::Or:
941 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000942 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
943 RHSKnownZero, RHSKnownOne, Depth+1) ||
944 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000945 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 return I;
947 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
948 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // If all of the demanded bits are known zero on one side, return the other.
951 // These bits cannot contribute to the result of the 'or'.
952 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
953 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
956 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000958
959 // If all of the potentially set bits on one side are known to be set on
960 // the other side, just use the 'other' side.
961 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
962 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
965 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000969 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000970 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000971
972 // Output known-0 bits are only known if clear in both the LHS & RHS.
973 RHSKnownZero &= LHSKnownZero;
974 // Output known-1 are known to be set if set in either the LHS | RHS.
975 RHSKnownOne |= LHSKnownOne;
976 break;
977 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979 RHSKnownZero, RHSKnownOne, Depth+1) ||
980 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 return I;
983 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
984 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000985
986 // If all of the demanded bits are known zero on one side, return the other.
987 // These bits cannot contribute to the result of the 'xor'.
988 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // Output known-0 bits are known if clear or set in both the LHS & RHS.
994 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
995 (RHSKnownOne & LHSKnownOne);
996 // Output known-1 are known to be set if set in only one of the LHS, RHS.
997 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
998 (RHSKnownOne & LHSKnownZero);
999
1000 // If all of the demanded bits are known to be zero on one side or the
1001 // other, turn this into an *inclusive* or.
1002 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1003 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1004 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001005 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001008 }
1009
1010 // If all of the demanded bits on one side are known, and all of the set
1011 // bits on that side are also known to be set on the other side, turn this
1012 // into an AND, as we know the bits will be cleared.
1013 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1014 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1015 // all known
1016 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001017 Constant *AndC = Constant::getIntegerValue(VTy,
1018 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001020 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022 }
1023 }
1024
1025 // If the RHS is a constant, see if we can simplify it.
1026 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001027 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001029
1030 RHSKnownZero = KnownZeroOut;
1031 RHSKnownOne = KnownOneOut;
1032 break;
1033 }
1034 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1036 RHSKnownZero, RHSKnownOne, Depth+1) ||
1037 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001038 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001039 return I;
1040 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1041 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001042
1043 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001044 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1045 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001046 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001047
1048 // Only known if known in both the LHS and RHS.
1049 RHSKnownOne &= LHSKnownOne;
1050 RHSKnownZero &= LHSKnownZero;
1051 break;
1052 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001053 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001054 DemandedMask.zext(truncBf);
1055 RHSKnownZero.zext(truncBf);
1056 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001057 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001058 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001059 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001060 DemandedMask.trunc(BitWidth);
1061 RHSKnownZero.trunc(BitWidth);
1062 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001063 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001064 break;
1065 }
1066 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001067 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001069
1070 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1071 if (const VectorType *SrcVTy =
1072 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1073 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1074 // Don't touch a bitcast between vectors of different element counts.
1075 return false;
1076 } else
1077 // Don't touch a scalar-to-vector bitcast.
1078 return false;
1079 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1080 // Don't touch a vector-to-scalar bitcast.
1081 return false;
1082
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001084 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 return I;
1086 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 break;
1088 case Instruction::ZExt: {
1089 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001090 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001091
Zhou Shengd48653a2007-03-29 04:45:55 +00001092 DemandedMask.trunc(SrcBitWidth);
1093 RHSKnownZero.trunc(SrcBitWidth);
1094 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001095 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001096 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001098 DemandedMask.zext(BitWidth);
1099 RHSKnownZero.zext(BitWidth);
1100 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001101 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001102 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001103 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001104 break;
1105 }
1106 case Instruction::SExt: {
1107 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001108 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001109
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001111 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
Zhou Sheng01542f32007-03-29 02:26:30 +00001113 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001114 // If any of the sign extended bits are demanded, we know that the sign
1115 // bit is demanded.
1116 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001117 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001118
Zhou Shengd48653a2007-03-29 04:45:55 +00001119 InputDemandedBits.trunc(SrcBitWidth);
1120 RHSKnownZero.trunc(SrcBitWidth);
1121 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001123 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 InputDemandedBits.zext(BitWidth);
1126 RHSKnownZero.zext(BitWidth);
1127 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001129
1130 // If the sign bit of the input is known set or clear, then we know the
1131 // top bits of the result.
1132
1133 // If the input sign bit is known zero, or if the NewBits are not demanded
1134 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001135 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1138 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001139 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001141 }
1142 break;
1143 }
1144 case Instruction::Add: {
1145 // Figure out what the input bits are. If the top bits of the and result
1146 // are not demanded, then the add doesn't demand them from its input
1147 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001149
1150 // If there is a constant on the RHS, there are a variety of xformations
1151 // we can do.
1152 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1153 // If null, this should be simplified elsewhere. Some of the xforms here
1154 // won't work if the RHS is zero.
1155 if (RHS->isZero())
1156 break;
1157
1158 // If the top bit of the output is demanded, demand everything from the
1159 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001160 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001161
1162 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001165 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001166
1167 // If the RHS of the add has bits set that can't affect the input, reduce
1168 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001169 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // Avoid excess work.
1173 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1174 break;
1175
1176 // Turn it into OR if input bits are zero.
1177 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1178 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001179 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001180 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001181 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001182 }
1183
1184 // We can say something about the output known-zero and known-one bits,
1185 // depending on potential carries from the input constant and the
1186 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1187 // bits set and the RHS constant is 0x01001, then we know we have a known
1188 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1189
1190 // To compute this, we first compute the potential carry bits. These are
1191 // the bits which may be modified. I'm not aware of a better way to do
1192 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001193 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001194 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001195
1196 // Now that we know which bits have carries, compute the known-1/0 sets.
1197
1198 // Bits are known one if they are known zero in one operand and one in the
1199 // other, and there is no input carry.
1200 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1201 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1202
1203 // Bits are known zero if they are known zero in both operands and there
1204 // is no input carry.
1205 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1206 } else {
1207 // If the high-bits of this ADD are not demanded, then it does not demand
1208 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001209 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 // Right fill the mask of bits for this ADD to demand the most
1211 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001212 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214 LHSKnownZero, LHSKnownOne, Depth+1) ||
1215 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 }
1219 }
1220 break;
1221 }
1222 case Instruction::Sub:
1223 // If the high-bits of this SUB are not demanded, then it does not demand
1224 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 // Right fill the mask of bits for this SUB to demand the most
1227 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001228 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001229 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001230 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1231 LHSKnownZero, LHSKnownOne, Depth+1) ||
1232 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001234 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001236 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1237 // the known zeros and ones.
1238 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 break;
1240 case Instruction::Shl:
1241 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001242 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001243 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001244 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001246 return I;
1247 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 RHSKnownZero <<= ShiftAmt;
1249 RHSKnownOne <<= ShiftAmt;
1250 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001251 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001252 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 }
1254 break;
1255 case Instruction::LShr:
1256 // For a logical shift right
1257 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001258 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001259
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001261 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001262 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 return I;
1265 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1267 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001268 if (ShiftAmt) {
1269 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001270 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001271 RHSKnownZero |= HighBits; // high bits known zero.
1272 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 }
1274 break;
1275 case Instruction::AShr:
1276 // If this is an arithmetic shift right and only the low-bit is set, we can
1277 // always convert this into a logical shr, even if the shift amount is
1278 // variable. The low bit of the shift cannot be an input sign bit unless
1279 // the shift amount is >= the size of the datatype, which is undefined.
1280 if (DemandedMask == 1) {
1281 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001282 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001286
1287 // If the sign bit is the only bit demanded by this ashr, then there is no
1288 // need to do it, the shift doesn't change the high bit.
1289 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001291
1292 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001293 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001294
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001297 // If any of the "high bits" are demanded, we should set the sign bit as
1298 // demanded.
1299 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1300 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001301 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001302 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 return I;
1304 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001306 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1308 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1309
1310 // Handle the sign bits.
1311 APInt SignBit(APInt::getSignBit(BitWidth));
1312 // Adjust to where it is now in the mask.
1313 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1314
1315 // If the input sign bit is known to be zero, or if none of the top bits
1316 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001317 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001318 (HighBits & ~DemandedMask) == HighBits) {
1319 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1324 RHSKnownOne |= HighBits;
1325 }
1326 }
1327 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001328 case Instruction::SRem:
1329 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001330 APInt RA = Rem->getValue().abs();
1331 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001332 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001333 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001334
Nick Lewycky8e394322008-11-02 02:41:50 +00001335 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001336 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001338 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001340
1341 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1342 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343
1344 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001347 }
1348 }
1349 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001350 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001351 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1352 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1354 KnownZero2, KnownOne2, Depth+1) ||
1355 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001356 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001357 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001358
Chris Lattner455e9ab2009-01-21 18:09:24 +00001359 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001360 Leaders = std::max(Leaders,
1361 KnownZero2.countLeadingOnes());
1362 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001363 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001364 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001365 case Instruction::Call:
1366 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1367 switch (II->getIntrinsicID()) {
1368 default: break;
1369 case Intrinsic::bswap: {
1370 // If the only bits demanded come from one byte of the bswap result,
1371 // just shift the input byte into position to eliminate the bswap.
1372 unsigned NLZ = DemandedMask.countLeadingZeros();
1373 unsigned NTZ = DemandedMask.countTrailingZeros();
1374
1375 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1376 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1377 // have 14 leading zeros, round to 8.
1378 NLZ &= ~7;
1379 NTZ &= ~7;
1380 // If we need exactly one byte, we can do this transformation.
1381 if (BitWidth-NLZ-NTZ == 8) {
1382 unsigned ResultBit = NTZ;
1383 unsigned InputBit = BitWidth-NTZ-8;
1384
1385 // Replace this with either a left or right shift to get the byte into
1386 // the right place.
1387 Instruction *NewVal;
1388 if (InputBit > ResultBit)
1389 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001390 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001391 else
1392 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001393 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001394 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001395 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001396 }
1397
1398 // TODO: Could compute known zero/one bits based on the input.
1399 break;
1400 }
1401 }
1402 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001403 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001404 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001405 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001406
1407 // If the client is only demanding bits that we know, return the known
1408 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001409 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1410 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 return false;
1412}
1413
Chris Lattner867b99f2006-10-05 06:55:50 +00001414
Mon P Wangaeb06d22008-11-10 04:46:22 +00001415/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001416/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001417/// actually used by the caller. This method analyzes which elements of the
1418/// operand are undef and returns that information in UndefElts.
1419///
1420/// If the information about demanded elements can be used to simplify the
1421/// operation, the operation is simplified, then the resultant value is
1422/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001423Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1424 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001425 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001426 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001427 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001428 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001429
1430 if (isa<UndefValue>(V)) {
1431 // If the entire vector is undefined, just return this info.
1432 UndefElts = EltMask;
1433 return 0;
1434 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1435 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001436 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001437 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001438
Chris Lattner867b99f2006-10-05 06:55:50 +00001439 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1441 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001442 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001443
1444 std::vector<Constant*> Elts;
1445 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001446 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001447 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001448 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001449 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1450 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001451 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 } else { // Otherwise, defined.
1453 Elts.push_back(CP->getOperand(i));
1454 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001455
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001457 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 return NewCP != CP ? NewCP : 0;
1459 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001460 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001462
1463 // Check if this is identity. If so, return 0 since we are not simplifying
1464 // anything.
1465 if (DemandedElts == ((1ULL << VWidth) -1))
1466 return 0;
1467
Reid Spencer9d6565a2007-02-15 02:26:10 +00001468 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001469 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001470 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001472 for (unsigned i = 0; i != VWidth; ++i) {
1473 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1474 Elts.push_back(Elt);
1475 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001477 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001478 }
1479
Dan Gohman488fbfc2008-09-09 18:11:14 +00001480 // Limit search depth.
1481 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001482 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001483
1484 // If multiple users are using the root value, procede with
1485 // simplification conservatively assuming that all elements
1486 // are needed.
1487 if (!V->hasOneUse()) {
1488 // Quit if we find multiple users of a non-root value though.
1489 // They'll be handled when it's their turn to be visited by
1490 // the main instcombine process.
1491 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001493 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001494
1495 // Conservatively assume that all elements are needed.
1496 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 }
1498
1499 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001500 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001501
1502 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001503 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001504 Value *TmpV;
1505 switch (I->getOpcode()) {
1506 default: break;
1507
1508 case Instruction::InsertElement: {
1509 // If this is a variable index, we don't know which element it overwrites.
1510 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001511 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 if (Idx == 0) {
1513 // Note that we can't propagate undef elt info, because we don't know
1514 // which elt is getting updated.
1515 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1516 UndefElts2, Depth+1);
1517 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1518 break;
1519 }
1520
1521 // If this is inserting an element that isn't demanded, remove this
1522 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001523 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001524 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 return AddSoonDeadInstToWorklist(*I, 0);
1526
1527 // Otherwise, the element inserted overwrites whatever was there, so the
1528 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001529 APInt DemandedElts2 = DemandedElts;
1530 DemandedElts2.clear(IdxNo);
1531 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001532 UndefElts, Depth+1);
1533 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1534
1535 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001536 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001537 break;
1538 }
1539 case Instruction::ShuffleVector: {
1540 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001541 uint64_t LHSVWidth =
1542 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001543 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001544 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001545 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001546 unsigned MaskVal = Shuffle->getMaskValue(i);
1547 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001548 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001549 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001550 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001551 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001552 else
Evan Cheng388df622009-02-03 10:05:09 +00001553 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 }
1555 }
1556 }
1557
Nate Begeman7b254672009-02-11 22:36:25 +00001558 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001559 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001560 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1562
Nate Begeman7b254672009-02-11 22:36:25 +00001563 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001564 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1565 UndefElts3, Depth+1);
1566 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1567
1568 bool NewUndefElts = false;
1569 for (unsigned i = 0; i < VWidth; i++) {
1570 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001571 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001572 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001573 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001574 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001575 NewUndefElts = true;
1576 UndefElts.set(i);
1577 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001579 if (UndefElts3[MaskVal - LHSVWidth]) {
1580 NewUndefElts = true;
1581 UndefElts.set(i);
1582 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001583 }
1584 }
1585
1586 if (NewUndefElts) {
1587 // Add additional discovered undefs.
1588 std::vector<Constant*> Elts;
1589 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001590 if (UndefElts[i])
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001591 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001592 else
Owen Andersoneed707b2009-07-24 23:12:02 +00001593 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001594 Shuffle->getMaskValue(i)));
1595 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001596 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 MadeChange = true;
1598 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001599 break;
1600 }
Chris Lattner69878332007-04-14 22:29:23 +00001601 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001602 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001603 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1604 if (!VTy) break;
1605 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001606 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001607 unsigned Ratio;
1608
1609 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001610 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001611 // elements as are demanded of us.
1612 Ratio = 1;
1613 InputDemandedElts = DemandedElts;
1614 } else if (VWidth > InVWidth) {
1615 // Untested so far.
1616 break;
1617
1618 // If there are more elements in the result than there are in the source,
1619 // then an input element is live if any of the corresponding output
1620 // elements are live.
1621 Ratio = VWidth/InVWidth;
1622 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001623 if (DemandedElts[OutIdx])
1624 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001625 }
1626 } else {
1627 // Untested so far.
1628 break;
1629
1630 // If there are more elements in the source than there are in the result,
1631 // then an input element is live if the corresponding output element is
1632 // live.
1633 Ratio = InVWidth/VWidth;
1634 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001635 if (DemandedElts[InIdx/Ratio])
1636 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001637 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001638
Chris Lattner69878332007-04-14 22:29:23 +00001639 // div/rem demand all inputs, because they don't want divide by zero.
1640 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1641 UndefElts2, Depth+1);
1642 if (TmpV) {
1643 I->setOperand(0, TmpV);
1644 MadeChange = true;
1645 }
1646
1647 UndefElts = UndefElts2;
1648 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001649 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001650 // If there are more elements in the result than there are in the source,
1651 // then an output element is undef if the corresponding input element is
1652 // undef.
1653 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001654 if (UndefElts2[OutIdx/Ratio])
1655 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001656 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001657 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001658 // If there are more elements in the source than there are in the result,
1659 // then a result element is undef if all of the corresponding input
1660 // elements are undef.
1661 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1662 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001663 if (!UndefElts2[InIdx]) // Not undef?
1664 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001665 }
1666 break;
1667 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001668 case Instruction::And:
1669 case Instruction::Or:
1670 case Instruction::Xor:
1671 case Instruction::Add:
1672 case Instruction::Sub:
1673 case Instruction::Mul:
1674 // div/rem demand all inputs, because they don't want divide by zero.
1675 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1676 UndefElts, Depth+1);
1677 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1678 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1679 UndefElts2, Depth+1);
1680 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1681
1682 // Output elements are undefined if both are undefined. Consider things
1683 // like undef&0. The result is known zero, not undef.
1684 UndefElts &= UndefElts2;
1685 break;
1686
1687 case Instruction::Call: {
1688 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1689 if (!II) break;
1690 switch (II->getIntrinsicID()) {
1691 default: break;
1692
1693 // Binary vector operations that work column-wise. A dest element is a
1694 // function of the corresponding input elements from the two inputs.
1695 case Intrinsic::x86_sse_sub_ss:
1696 case Intrinsic::x86_sse_mul_ss:
1697 case Intrinsic::x86_sse_min_ss:
1698 case Intrinsic::x86_sse_max_ss:
1699 case Intrinsic::x86_sse2_sub_sd:
1700 case Intrinsic::x86_sse2_mul_sd:
1701 case Intrinsic::x86_sse2_min_sd:
1702 case Intrinsic::x86_sse2_max_sd:
1703 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1704 UndefElts, Depth+1);
1705 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1706 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1707 UndefElts2, Depth+1);
1708 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1709
1710 // If only the low elt is demanded and this is a scalarizable intrinsic,
1711 // scalarize it now.
1712 if (DemandedElts == 1) {
1713 switch (II->getIntrinsicID()) {
1714 default: break;
1715 case Intrinsic::x86_sse_sub_ss:
1716 case Intrinsic::x86_sse_mul_ss:
1717 case Intrinsic::x86_sse2_sub_sd:
1718 case Intrinsic::x86_sse2_mul_sd:
1719 // TODO: Lower MIN/MAX/ABS/etc
1720 Value *LHS = II->getOperand(1);
1721 Value *RHS = II->getOperand(2);
1722 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001723 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001724 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001725 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001726 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001727
1728 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001729 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001730 case Intrinsic::x86_sse_sub_ss:
1731 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001732 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001733 II->getName()), *II);
1734 break;
1735 case Intrinsic::x86_sse_mul_ss:
1736 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001737 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001738 II->getName()), *II);
1739 break;
1740 }
1741
1742 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001743 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001744 UndefValue::get(II->getType()), TmpV,
Owen Andersoneed707b2009-07-24 23:12:02 +00001745 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001746 InsertNewInstBefore(New, *II);
1747 AddSoonDeadInstToWorklist(*II, 0);
1748 return New;
1749 }
1750 }
1751
1752 // Output elements are undefined if both are undefined. Consider things
1753 // like undef&0. The result is known zero, not undef.
1754 UndefElts &= UndefElts2;
1755 break;
1756 }
1757 break;
1758 }
1759 }
1760 return MadeChange ? I : 0;
1761}
1762
Dan Gohman45b4e482008-05-19 22:14:15 +00001763
Chris Lattner564a7272003-08-13 19:01:45 +00001764/// AssociativeOpt - Perform an optimization on an associative operator. This
1765/// function is designed to check a chain of associative operators for a
1766/// potential to apply a certain optimization. Since the optimization may be
1767/// applicable if the expression was reassociated, this checks the chain, then
1768/// reassociates the expression as necessary to expose the optimization
1769/// opportunity. This makes use of a special Functor, which must define
1770/// 'shouldApply' and 'apply' methods.
1771///
1772template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001773static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001774 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001775 unsigned Opcode = Root.getOpcode();
1776 Value *LHS = Root.getOperand(0);
1777
1778 // Quick check, see if the immediate LHS matches...
1779 if (F.shouldApply(LHS))
1780 return F.apply(Root);
1781
1782 // Otherwise, if the LHS is not of the same opcode as the root, return.
1783 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001784 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001785 // Should we apply this transform to the RHS?
1786 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1787
1788 // If not to the RHS, check to see if we should apply to the LHS...
1789 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1790 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1791 ShouldApply = true;
1792 }
1793
1794 // If the functor wants to apply the optimization to the RHS of LHSI,
1795 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1796 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001797 // Now all of the instructions are in the current basic block, go ahead
1798 // and perform the reassociation.
1799 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1800
1801 // First move the selected RHS to the LHS of the root...
1802 Root.setOperand(0, LHSI->getOperand(1));
1803
1804 // Make what used to be the LHS of the root be the user of the root...
1805 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001806 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001807 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001808 return 0;
1809 }
Chris Lattner65725312004-04-16 18:08:07 +00001810 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001811 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001812 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001813 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001814 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001815
1816 // Now propagate the ExtraOperand down the chain of instructions until we
1817 // get to LHSI.
1818 while (TmpLHSI != LHSI) {
1819 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001820 // Move the instruction to immediately before the chain we are
1821 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001822 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001823 ARI = NextLHSI;
1824
Chris Lattner564a7272003-08-13 19:01:45 +00001825 Value *NextOp = NextLHSI->getOperand(1);
1826 NextLHSI->setOperand(1, ExtraOperand);
1827 TmpLHSI = NextLHSI;
1828 ExtraOperand = NextOp;
1829 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001830
Chris Lattner564a7272003-08-13 19:01:45 +00001831 // Now that the instructions are reassociated, have the functor perform
1832 // the transformation...
1833 return F.apply(Root);
1834 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001835
Chris Lattner564a7272003-08-13 19:01:45 +00001836 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1837 }
1838 return 0;
1839}
1840
Dan Gohman844731a2008-05-13 00:00:25 +00001841namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001842
Nick Lewycky02d639f2008-05-23 04:34:58 +00001843// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001844struct AddRHS {
1845 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001846 LLVMContext *Context;
1847 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001848 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1849 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001850 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001851 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001852 }
1853};
1854
1855// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1856// iff C1&C2 == 0
1857struct AddMaskingAnd {
1858 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001859 LLVMContext *Context;
1860 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001861 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001862 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001863 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001864 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001865 }
1866 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001867 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001868 }
1869};
1870
Dan Gohman844731a2008-05-13 00:00:25 +00001871}
1872
Chris Lattner6e7ba452005-01-01 16:22:27 +00001873static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001874 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001875 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001876
Reid Spencer3da59db2006-11-27 01:05:10 +00001877 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001878 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001879 }
1880
Chris Lattner2eefe512004-04-09 19:05:30 +00001881 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001882 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1883 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001884
Chris Lattner2eefe512004-04-09 19:05:30 +00001885 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1886 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001887 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1888 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001889 }
1890
1891 Value *Op0 = SO, *Op1 = ConstOperand;
1892 if (!ConstIsRHS)
1893 std::swap(Op0, Op1);
1894 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001895 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001896 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001897 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001898 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1899 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001900 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001901 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001902 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001903 return IC->InsertNewInstBefore(New, I);
1904}
1905
1906// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1907// constant as the other operand, try to fold the binary operator into the
1908// select arguments. This also works for Cast instructions, which obviously do
1909// not have a second operand.
1910static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1911 InstCombiner *IC) {
1912 // Don't modify shared select instructions
1913 if (!SI->hasOneUse()) return 0;
1914 Value *TV = SI->getOperand(1);
1915 Value *FV = SI->getOperand(2);
1916
1917 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001918 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001919 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001920
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1922 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1923
Gabor Greif051a9502008-04-06 20:25:17 +00001924 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1925 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001926 }
1927 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001928}
1929
Chris Lattner4e998b22004-09-29 05:07:12 +00001930
1931/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1932/// node as operand #0, see if we can fold the instruction into the PHI (which
1933/// is only possible if all operands to the PHI are constants).
1934Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1935 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001936 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001937 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001938
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001939 // Check to see if all of the operands of the PHI are constants. If there is
1940 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001941 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001942 BasicBlock *NonConstBB = 0;
1943 for (unsigned i = 0; i != NumPHIValues; ++i)
1944 if (!isa<Constant>(PN->getIncomingValue(i))) {
1945 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001946 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001947 NonConstBB = PN->getIncomingBlock(i);
1948
1949 // If the incoming non-constant value is in I's block, we have an infinite
1950 // loop.
1951 if (NonConstBB == I.getParent())
1952 return 0;
1953 }
1954
1955 // If there is exactly one non-constant value, we can insert a copy of the
1956 // operation in that block. However, if this is a critical edge, we would be
1957 // inserting the computation one some other paths (e.g. inside a loop). Only
1958 // do this if the pred block is unconditionally branching into the phi block.
1959 if (NonConstBB) {
1960 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1961 if (!BI || !BI->isUnconditional()) return 0;
1962 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001963
1964 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001965 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001966 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001967 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001968 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001969
1970 // Next, add all of the operands to the PHI.
1971 if (I.getNumOperands() == 2) {
1972 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001973 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001974 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001975 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001976 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001977 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001978 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001979 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001980 } else {
1981 assert(PN->getIncomingBlock(i) == NonConstBB);
1982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001983 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001984 PN->getIncomingValue(i), C, "phitmp",
1985 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001986 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001987 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001988 CI->getPredicate(),
1989 PN->getIncomingValue(i), C, "phitmp",
1990 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001991 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001992 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993
Chris Lattnerdbab3862007-03-02 21:28:56 +00001994 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001995 }
1996 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001997 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001998 } else {
1999 CastInst *CI = cast<CastInst>(&I);
2000 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002001 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 Value *InV;
2003 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002004 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002005 } else {
2006 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002007 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002008 I.getType(), "phitmp",
2009 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002010 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002011 }
2012 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002013 }
2014 }
2015 return ReplaceInstUsesWith(I, NewPN);
2016}
2017
Chris Lattner2454a2e2008-01-29 06:52:45 +00002018
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002019/// WillNotOverflowSignedAdd - Return true if we can prove that:
2020/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2021/// This basically requires proving that the add in the original type would not
2022/// overflow to change the sign bit or have a carry out.
2023bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2024 // There are different heuristics we can use for this. Here are some simple
2025 // ones.
2026
2027 // Add has the property that adding any two 2's complement numbers can only
2028 // have one carry bit which can change a sign. As such, if LHS and RHS each
2029 // have at least two sign bits, we know that the addition of the two values will
2030 // sign extend fine.
2031 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2032 return true;
2033
2034
2035 // If one of the operands only has one non-zero bit, and if the other operand
2036 // has a known-zero bit in a more significant place than it (not including the
2037 // sign bit) the ripple may go up to and fill the zero, but won't change the
2038 // sign. For example, (X & ~4) + 1.
2039
2040 // TODO: Implement.
2041
2042 return false;
2043}
2044
Chris Lattner2454a2e2008-01-29 06:52:45 +00002045
Chris Lattner7e708292002-06-25 16:13:24 +00002046Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002047 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002048 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002049
Chris Lattner66331a42004-04-10 22:01:55 +00002050 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002051 // X + undef -> undef
2052 if (isa<UndefValue>(RHS))
2053 return ReplaceInstUsesWith(I, RHS);
2054
Chris Lattner66331a42004-04-10 22:01:55 +00002055 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002056 if (RHSC->isNullValue())
2057 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002058
Chris Lattner66331a42004-04-10 22:01:55 +00002059 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002060 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002061 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002062 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002063 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002064 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002065
2066 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2067 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002068 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002069 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002070
Eli Friedman709b33d2009-07-13 22:27:52 +00002071 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002072 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002073 if (ZI->getSrcTy() == Type::Int1Ty)
2074 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002075 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002076
2077 if (isa<PHINode>(LHS))
2078 if (Instruction *NV = FoldOpIntoPhi(I))
2079 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002080
Chris Lattner4f637d42006-01-06 17:59:59 +00002081 ConstantInt *XorRHS = 0;
2082 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002083 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002084 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002085 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002086 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002087
Zhou Sheng4351c642007-04-02 08:20:41 +00002088 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002089 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2090 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002091 do {
2092 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002093 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2094 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002095 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2096 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002097 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002098 if (!MaskedValueIsZero(XorLHS,
2099 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002100 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002101 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002102 }
2103 }
2104 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002105 C0080Val = APIntOps::lshr(C0080Val, Size);
2106 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2107 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002108
Reid Spencer35c38852007-03-28 01:36:16 +00002109 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002110 // with funny bit widths then this switch statement should be removed. It
2111 // is just here to get the size of the "middle" type back up to something
2112 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002113 const Type *MiddleType = 0;
2114 switch (Size) {
2115 default: break;
2116 case 32: MiddleType = Type::Int32Ty; break;
2117 case 16: MiddleType = Type::Int16Ty; break;
2118 case 8: MiddleType = Type::Int8Ty; break;
2119 }
2120 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002121 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002122 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002123 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002124 }
2125 }
Chris Lattner66331a42004-04-10 22:01:55 +00002126 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002127
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002128 if (I.getType() == Type::Int1Ty)
2129 return BinaryOperator::CreateXor(LHS, RHS);
2130
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002131 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002132 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002133 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2134 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002135
2136 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2137 if (RHSI->getOpcode() == Instruction::Sub)
2138 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2139 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2140 }
2141 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2142 if (LHSI->getOpcode() == Instruction::Sub)
2143 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2144 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2145 }
Robert Bocchino71698282004-07-27 21:02:21 +00002146 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002147
Chris Lattner5c4afb92002-05-08 22:46:53 +00002148 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002149 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002150 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002151 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002152 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002153 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002154 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002155 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002156 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002157 }
2158
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002160 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002161
2162 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002163 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002164 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002166
Misha Brukmanfd939082005-04-21 23:48:37 +00002167
Chris Lattner50af16a2004-11-13 19:50:12 +00002168 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002169 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002170 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002171 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002172
2173 // X*C1 + X*C2 --> X * (C1+C2)
2174 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002175 if (X == dyn_castFoldableMul(RHS, C1, Context))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002176 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002177 }
2178
2179 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002180 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2181 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002182
Chris Lattnere617c9e2007-01-05 02:17:46 +00002183 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002184 if (dyn_castNotVal(LHS, Context) == RHS ||
2185 dyn_castNotVal(RHS, Context) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002186 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002187
Chris Lattnerad3448c2003-02-18 19:57:07 +00002188
Chris Lattner564a7272003-08-13 19:01:45 +00002189 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002190 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002191 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002192 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002193
2194 // A+B --> A|B iff A and B have no bits set in common.
2195 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2196 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2197 APInt LHSKnownOne(IT->getBitWidth(), 0);
2198 APInt LHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2200 if (LHSKnownZero != 0) {
2201 APInt RHSKnownOne(IT->getBitWidth(), 0);
2202 APInt RHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2204
2205 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002206 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002207 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002208 }
2209 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002210
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002211 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002212 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002213 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002214 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2215 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002216 if (W != Y) {
2217 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002218 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002219 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002220 std::swap(W, X);
2221 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002222 std::swap(Y, Z);
2223 std::swap(W, X);
2224 }
2225 }
2226
2227 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002228 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002229 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002230 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002231 }
2232 }
2233 }
2234
Chris Lattner6b032052003-10-02 15:11:26 +00002235 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002236 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002237 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002238 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002239
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002240 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002241 if (LHS->hasOneUse() &&
2242 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002243 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002244 if (Anded == CRHS) {
2245 // See if all bits from the first bit set in the Add RHS up are included
2246 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002247 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002248
2249 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002250 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002251
2252 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002253 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002254
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002255 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2256 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002257 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002259 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002260 }
2261 }
2262 }
2263
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002264 // Try to fold constant add into select arguments.
2265 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002266 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002267 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002268 }
2269
Chris Lattner42790482007-12-20 01:56:58 +00002270 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002271 {
2272 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002273 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002274 if (!SI) {
2275 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002276 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 }
Chris Lattner42790482007-12-20 01:56:58 +00002278 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002279 Value *TV = SI->getTrueValue();
2280 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002281 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002282
2283 // Can we fold the add into the argument of the select?
2284 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002285 if (match(FV, m_Zero(), *Context) &&
2286 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002288 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002289 if (match(TV, m_Zero(), *Context) &&
2290 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002291 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002292 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002293 }
2294 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002295
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002296 // Check for (add (sext x), y), see if we can merge this into an
2297 // integer add followed by a sext.
2298 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2299 // (add (sext x), cst) --> (sext (add x, cst'))
2300 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2301 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002302 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002303 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002304 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002305 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2306 // Insert the new, smaller add.
2307 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2308 CI, "addconv");
2309 InsertNewInstBefore(NewAdd, I);
2310 return new SExtInst(NewAdd, I.getType());
2311 }
2312 }
2313
2314 // (add (sext x), (sext y)) --> (sext (add int x, y))
2315 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2316 // Only do this if x/y have the same type, if at last one of them has a
2317 // single use (so we don't increase the number of sexts), and if the
2318 // integer add will not overflow.
2319 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2320 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2321 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2322 RHSConv->getOperand(0))) {
2323 // Insert the new integer add.
2324 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2325 RHSConv->getOperand(0),
2326 "addconv");
2327 InsertNewInstBefore(NewAdd, I);
2328 return new SExtInst(NewAdd, I.getType());
2329 }
2330 }
2331 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002332
2333 return Changed ? &I : 0;
2334}
2335
2336Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2337 bool Changed = SimplifyCommutative(I);
2338 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2339
2340 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2341 // X + 0 --> X
2342 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002343 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002344 (I.getType())->getValueAPF()))
2345 return ReplaceInstUsesWith(I, LHS);
2346 }
2347
2348 if (isa<PHINode>(LHS))
2349 if (Instruction *NV = FoldOpIntoPhi(I))
2350 return NV;
2351 }
2352
2353 // -A + B --> B - A
2354 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002355 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002356 return BinaryOperator::CreateFSub(RHS, LHSV);
2357
2358 // A + -B --> A - B
2359 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002360 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002361 return BinaryOperator::CreateFSub(LHS, V);
2362
2363 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2364 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2365 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2366 return ReplaceInstUsesWith(I, LHS);
2367
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002368 // Check for (add double (sitofp x), y), see if we can merge this into an
2369 // integer add followed by a promotion.
2370 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2371 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2372 // ... if the constant fits in the integer value. This is useful for things
2373 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2374 // requires a constant pool load, and generally allows the add to be better
2375 // instcombined.
2376 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2377 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002378 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002379 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002380 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002381 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2382 // Insert the new integer add.
2383 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2384 CI, "addconv");
2385 InsertNewInstBefore(NewAdd, I);
2386 return new SIToFPInst(NewAdd, I.getType());
2387 }
2388 }
2389
2390 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2391 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2392 // Only do this if x/y have the same type, if at last one of them has a
2393 // single use (so we don't increase the number of int->fp conversions),
2394 // and if the integer add will not overflow.
2395 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2396 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2397 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2398 RHSConv->getOperand(0))) {
2399 // Insert the new integer add.
2400 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2401 RHSConv->getOperand(0),
2402 "addconv");
2403 InsertNewInstBefore(NewAdd, I);
2404 return new SIToFPInst(NewAdd, I.getType());
2405 }
2406 }
2407 }
2408
Chris Lattner7e708292002-06-25 16:13:24 +00002409 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002410}
2411
Chris Lattner7e708292002-06-25 16:13:24 +00002412Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002414
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002415 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002417
Chris Lattner233f7dc2002-08-12 21:17:25 +00002418 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002419 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002420 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002421
Chris Lattnere87597f2004-10-16 18:11:37 +00002422 if (isa<UndefValue>(Op0))
2423 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2424 if (isa<UndefValue>(Op1))
2425 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2426
Chris Lattnerd65460f2003-11-05 01:06:05 +00002427 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2428 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002429 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002430 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002431
Chris Lattnerd65460f2003-11-05 01:06:05 +00002432 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002433 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002434 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002435 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002436
Chris Lattner76b7a062007-01-15 07:02:54 +00002437 // -(X >>u 31) -> (X >>s 31)
2438 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002439 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002440 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002441 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002442 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002443 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002444 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002445 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002446 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002448 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002449 }
2450 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002451 }
2452 else if (SI->getOpcode() == Instruction::AShr) {
2453 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002455 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002456 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002457 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002459 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002460 }
2461 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002462 }
2463 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002464 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002465
2466 // Try to fold constant sub into select arguments.
2467 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002468 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002469 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002470
2471 // C - zext(bool) -> bool ? C - 1 : C
2472 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2473 if (ZI->getSrcTy() == Type::Int1Ty)
2474 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002475 }
2476
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002477 if (I.getType() == Type::Int1Ty)
2478 return BinaryOperator::CreateXor(Op0, Op1);
2479
Chris Lattner43d84d62005-04-07 16:15:25 +00002480 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002481 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002483 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2484 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002485 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002486 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2487 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002488 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2489 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2490 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002491 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002492 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002493 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002494 }
2495
Chris Lattnerfd059242003-10-15 16:48:29 +00002496 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2498 // is not used by anyone else...
2499 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002500 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002501 // Swap the two operands of the subexpr...
2502 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2503 Op1I->setOperand(0, IIOp1);
2504 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002505
Chris Lattnera2881962003-02-18 19:28:33 +00002506 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002507 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002508 }
2509
2510 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2511 //
2512 if (Op1I->getOpcode() == Instruction::And &&
2513 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2514 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2515
Chris Lattnerf523d062004-06-09 05:08:07 +00002516 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002517 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2518 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002519 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002520 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002521
Reid Spencerac5209e2006-10-16 23:08:08 +00002522 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002523 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002524 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002525 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002526 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002527 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002528 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002529
Chris Lattnerad3448c2003-02-18 19:57:07 +00002530 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002531 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002532 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2533 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002534 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002535 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002537 }
Chris Lattner40371712002-05-09 01:29:19 +00002538 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002539 }
Chris Lattnera2881962003-02-18 19:28:33 +00002540
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002541 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2542 if (Op0I->getOpcode() == Instruction::Add) {
2543 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2544 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2545 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2546 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2547 } else if (Op0I->getOpcode() == Instruction::Sub) {
2548 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002549 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2550 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002551 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002552 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002553
Chris Lattner50af16a2004-11-13 19:50:12 +00002554 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002555 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002556 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002557 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002558
Chris Lattner50af16a2004-11-13 19:50:12 +00002559 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002560 if (X == dyn_castFoldableMul(Op1, C2, Context))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002561 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002562 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002563 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002564}
2565
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002566Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002570 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002571 return BinaryOperator::CreateFAdd(Op0, V);
2572
2573 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2574 if (Op1I->getOpcode() == Instruction::FAdd) {
2575 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002576 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2577 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002578 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002579 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2580 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002581 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002582 }
2583
2584 return 0;
2585}
2586
Chris Lattnera0141b92007-07-15 20:42:37 +00002587/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2588/// comparison only checks the sign bit. If it only checks the sign bit, set
2589/// TrueIfSigned if the result of the comparison is true when the input value is
2590/// signed.
2591static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2592 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002593 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002594 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2595 TrueIfSigned = true;
2596 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002597 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2598 TrueIfSigned = true;
2599 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002600 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2601 TrueIfSigned = false;
2602 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002603 case ICmpInst::ICMP_UGT:
2604 // True if LHS u> RHS and RHS == high-bit-mask - 1
2605 TrueIfSigned = true;
2606 return RHS->getValue() ==
2607 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2608 case ICmpInst::ICMP_UGE:
2609 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2610 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002611 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002612 default:
2613 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002614 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002615}
2616
Chris Lattner7e708292002-06-25 16:13:24 +00002617Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002618 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002619 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002620
Eli Friedman1694e092009-07-18 09:12:15 +00002621 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002622 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002623
Chris Lattner233f7dc2002-08-12 21:17:25 +00002624 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002625 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2626 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002627
2628 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002629 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002630 if (SI->getOpcode() == Instruction::Shl)
2631 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002632 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002633 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002634
Zhou Sheng843f07672007-04-19 05:39:12 +00002635 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002636 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2637 if (CI->equalsInt(1)) // X * 1 == X
2638 return ReplaceInstUsesWith(I, Op0);
2639 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002640 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002641
Zhou Sheng97b52c22007-03-29 01:57:21 +00002642 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002643 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002644 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002645 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002646 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002647 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002648 if (Op1->isNullValue())
2649 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002650
2651 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2652 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002653 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002654
2655 // As above, vector X*splat(1.0) -> X in all defined cases.
2656 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002657 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2658 if (CI->equalsInt(1))
2659 return ReplaceInstUsesWith(I, Op0);
2660 }
2661 }
Chris Lattnera2881962003-02-18 19:28:33 +00002662 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002663
2664 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2665 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002666 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002667 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002668 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002669 Op1, "tmp");
2670 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002671 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002672 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002674
2675 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002676
2677 // Try to fold constant mul into select arguments.
2678 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002679 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002680 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002681
2682 if (isa<PHINode>(Op0))
2683 if (Instruction *NV = FoldOpIntoPhi(I))
2684 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002685 }
2686
Owen Andersond672ecb2009-07-03 00:17:18 +00002687 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2688 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002690
Nick Lewycky0c730792008-11-21 07:33:58 +00002691 // (X / Y) * Y = X - (X % Y)
2692 // (X / Y) * -Y = (X % Y) - X
2693 {
2694 Value *Op1 = I.getOperand(1);
2695 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2696 if (!BO ||
2697 (BO->getOpcode() != Instruction::UDiv &&
2698 BO->getOpcode() != Instruction::SDiv)) {
2699 Op1 = Op0;
2700 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2701 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002702 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002703 if (BO && BO->hasOneUse() &&
2704 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2705 (BO->getOpcode() == Instruction::UDiv ||
2706 BO->getOpcode() == Instruction::SDiv)) {
2707 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2708
2709 Instruction *Rem;
2710 if (BO->getOpcode() == Instruction::UDiv)
2711 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2712 else
2713 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2714
2715 InsertNewInstBefore(Rem, I);
2716 Rem->takeName(BO);
2717
2718 if (Op1BO == Op1)
2719 return BinaryOperator::CreateSub(Op0BO, Rem);
2720 else
2721 return BinaryOperator::CreateSub(Rem, Op0BO);
2722 }
2723 }
2724
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002725 if (I.getType() == Type::Int1Ty)
2726 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2727
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002728 // If one of the operands of the multiply is a cast from a boolean value, then
2729 // we know the bool is either zero or one, so this is a 'masking' multiply.
2730 // See if we can simplify things based on how the boolean was originally
2731 // formed.
2732 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002733 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002734 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002735 BoolCast = CI;
2736 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002737 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002738 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002739 BoolCast = CI;
2740 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002741 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002742 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2743 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002744 bool TIS = false;
2745
Reid Spencere4d87aa2006-12-23 06:05:41 +00002746 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002747 // multiply into a shift/and combination.
2748 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002749 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2750 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002751 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002752 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002753 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002754 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002755 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002756 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002757 BoolCast->getOperand(0)->getName()+
2758 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002759
2760 // If the multiply type is not the same as the source type, sign extend
2761 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002762 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002763 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2764 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002765 Instruction::CastOps opcode =
2766 (SrcBits == DstBits ? Instruction::BitCast :
2767 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2768 V = InsertCastBefore(opcode, V, I.getType(), I);
2769 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002770
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002771 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002772 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002773 }
2774 }
2775 }
2776
Chris Lattner7e708292002-06-25 16:13:24 +00002777 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002778}
2779
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002780Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2781 bool Changed = SimplifyCommutative(I);
2782 Value *Op0 = I.getOperand(0);
2783
2784 // Simplify mul instructions with a constant RHS...
2785 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2786 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2787 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2788 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2789 if (Op1F->isExactlyValue(1.0))
2790 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2791 } else if (isa<VectorType>(Op1->getType())) {
2792 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2793 // As above, vector X*splat(1.0) -> X in all defined cases.
2794 if (Constant *Splat = Op1V->getSplatValue()) {
2795 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2796 if (F->isExactlyValue(1.0))
2797 return ReplaceInstUsesWith(I, Op0);
2798 }
2799 }
2800 }
2801
2802 // Try to fold constant mul into select arguments.
2803 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2804 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2805 return R;
2806
2807 if (isa<PHINode>(Op0))
2808 if (Instruction *NV = FoldOpIntoPhi(I))
2809 return NV;
2810 }
2811
Owen Andersond672ecb2009-07-03 00:17:18 +00002812 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2813 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002814 return BinaryOperator::CreateFMul(Op0v, Op1v);
2815
2816 return Changed ? &I : 0;
2817}
2818
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002819/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2820/// instruction.
2821bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2822 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2823
2824 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2825 int NonNullOperand = -1;
2826 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2827 if (ST->isNullValue())
2828 NonNullOperand = 2;
2829 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2830 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2831 if (ST->isNullValue())
2832 NonNullOperand = 1;
2833
2834 if (NonNullOperand == -1)
2835 return false;
2836
2837 Value *SelectCond = SI->getOperand(0);
2838
2839 // Change the div/rem to use 'Y' instead of the select.
2840 I.setOperand(1, SI->getOperand(NonNullOperand));
2841
2842 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2843 // problem. However, the select, or the condition of the select may have
2844 // multiple uses. Based on our knowledge that the operand must be non-zero,
2845 // propagate the known value for the select into other uses of it, and
2846 // propagate a known value of the condition into its other users.
2847
2848 // If the select and condition only have a single use, don't bother with this,
2849 // early exit.
2850 if (SI->use_empty() && SelectCond->hasOneUse())
2851 return true;
2852
2853 // Scan the current block backward, looking for other uses of SI.
2854 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2855
2856 while (BBI != BBFront) {
2857 --BBI;
2858 // If we found a call to a function, we can't assume it will return, so
2859 // information from below it cannot be propagated above it.
2860 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2861 break;
2862
2863 // Replace uses of the select or its condition with the known values.
2864 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2865 I != E; ++I) {
2866 if (*I == SI) {
2867 *I = SI->getOperand(NonNullOperand);
2868 AddToWorkList(BBI);
2869 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002870 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2871 ConstantInt::getFalse(*Context);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002872 AddToWorkList(BBI);
2873 }
2874 }
2875
2876 // If we past the instruction, quit looking for it.
2877 if (&*BBI == SI)
2878 SI = 0;
2879 if (&*BBI == SelectCond)
2880 SelectCond = 0;
2881
2882 // If we ran out of things to eliminate, break out of the loop.
2883 if (SelectCond == 0 && SI == 0)
2884 break;
2885
2886 }
2887 return true;
2888}
2889
2890
Reid Spencer1628cec2006-10-26 06:15:43 +00002891/// This function implements the transforms on div instructions that work
2892/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2893/// used by the visitors to those instructions.
2894/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002895Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002897
Chris Lattner50b2ca42008-02-19 06:12:18 +00002898 // undef / X -> 0 for integer.
2899 // undef / X -> undef for FP (the undef could be a snan).
2900 if (isa<UndefValue>(Op0)) {
2901 if (Op0->getType()->isFPOrFPVector())
2902 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002903 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002904 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002905
2906 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002907 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002908 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002909
Reid Spencer1628cec2006-10-26 06:15:43 +00002910 return 0;
2911}
Misha Brukmanfd939082005-04-21 23:48:37 +00002912
Reid Spencer1628cec2006-10-26 06:15:43 +00002913/// This function implements the transforms common to both integer division
2914/// instructions (udiv and sdiv). It is called by the visitors to those integer
2915/// division instructions.
2916/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002917Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002918 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2919
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002920 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002921 if (Op0 == Op1) {
2922 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002923 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002924 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002925 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002926 }
2927
Owen Andersoneed707b2009-07-24 23:12:02 +00002928 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002929 return ReplaceInstUsesWith(I, CI);
2930 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002931
Reid Spencer1628cec2006-10-26 06:15:43 +00002932 if (Instruction *Common = commonDivTransforms(I))
2933 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002934
2935 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2936 // This does not apply for fdiv.
2937 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2938 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002939
2940 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2941 // div X, 1 == X
2942 if (RHS->equalsInt(1))
2943 return ReplaceInstUsesWith(I, Op0);
2944
2945 // (X / C1) / C2 -> X / (C1*C2)
2946 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2947 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2948 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002949 if (MultiplyOverflows(RHS, LHSRHS,
2950 I.getOpcode()==Instruction::SDiv, Context))
Owen Andersona7235ea2009-07-31 20:28:14 +00002951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002952 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002953 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002954 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002955 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002956
Reid Spencerbca0e382007-03-23 20:05:17 +00002957 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002958 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2959 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2960 return R;
2961 if (isa<PHINode>(Op0))
2962 if (Instruction *NV = FoldOpIntoPhi(I))
2963 return NV;
2964 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002965 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002966
Chris Lattnera2881962003-02-18 19:28:33 +00002967 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002968 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002969 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002971
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002972 // It can't be division by zero, hence it must be division by one.
2973 if (I.getType() == Type::Int1Ty)
2974 return ReplaceInstUsesWith(I, Op0);
2975
Nick Lewycky895f0852008-11-27 20:21:08 +00002976 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2977 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2978 // div X, 1 == X
2979 if (X->isOne())
2980 return ReplaceInstUsesWith(I, Op0);
2981 }
2982
Reid Spencer1628cec2006-10-26 06:15:43 +00002983 return 0;
2984}
2985
2986Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2988
2989 // Handle the integer div common cases
2990 if (Instruction *Common = commonIDivTransforms(I))
2991 return Common;
2992
Reid Spencer1628cec2006-10-26 06:15:43 +00002993 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002994 // X udiv C^2 -> X >> C
2995 // Check to see if this is an unsigned division with an exact power of 2,
2996 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002997 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002998 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002999 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003000
3001 // X udiv C, where C >= signbit
3002 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003003 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3004 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003005 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003006 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003007 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003008 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003009 }
3010
3011 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003012 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 if (RHSI->getOpcode() == Instruction::Shl &&
3014 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003015 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003016 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003017 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003018 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003019 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003020 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003021 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003022 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003023 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003024 }
3025 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003026 }
3027
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3029 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003030 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003031 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003032 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003033 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003034 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003035 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003036 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003037 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003038 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003039 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003040 Op0, TC, SI->getName()+".t");
3041 TSI = InsertNewInstBefore(TSI, I);
3042
3043 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003044 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003045 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 Op0, FC, SI->getName()+".f");
3047 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003048
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003049 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003050 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003051 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003052 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003053 return 0;
3054}
3055
Reid Spencer1628cec2006-10-26 06:15:43 +00003056Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3058
3059 // Handle the integer div common cases
3060 if (Instruction *Common = commonIDivTransforms(I))
3061 return Common;
3062
3063 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3064 // sdiv X, -1 == -X
3065 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003066 return BinaryOperator::CreateNeg(*Context, Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003067
3068 // sdiv X, C --> ashr X, log2(C)
3069 if (cast<SDivOperator>(&I)->isExact() &&
3070 RHS->getValue().isNonNegative() &&
3071 RHS->getValue().isPowerOf2()) {
3072 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3073 RHS->getValue().exactLogBase2());
3074 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3075 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 }
3077
3078 // If the sign bits of both operands are zero (i.e. we can prove they are
3079 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003080 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003081 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003082 if (MaskedValueIsZero(Op0, Mask)) {
3083 if (MaskedValueIsZero(Op1, Mask)) {
3084 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3085 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086 }
3087 ConstantInt *ShiftedInt;
3088 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3089 ShiftedInt->getValue().isPowerOf2()) {
3090 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3091 // Safe because the only negative value (1 << Y) can take on is
3092 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3093 // the sign bit set.
3094 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003096 }
Eli Friedman8be17392009-07-18 09:53:21 +00003097 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003098
3099 return 0;
3100}
3101
3102Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3103 return commonDivTransforms(I);
3104}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003105
Reid Spencer0a783f72006-11-02 01:53:59 +00003106/// This function implements the transforms on rem instructions that work
3107/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3108/// is used by the visitors to those instructions.
3109/// @brief Transforms common to all three rem instructions
3110Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003112
Chris Lattner50b2ca42008-02-19 06:12:18 +00003113 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3114 if (I.getType()->isFPOrFPVector())
3115 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003116 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003117 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003118 if (isa<UndefValue>(Op1))
3119 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003120
3121 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003122 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3123 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003124
Reid Spencer0a783f72006-11-02 01:53:59 +00003125 return 0;
3126}
3127
3128/// This function implements the transforms common to both integer remainder
3129/// instructions (urem and srem). It is called by the visitors to those integer
3130/// remainder instructions.
3131/// @brief Common integer remainder transforms
3132Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135 if (Instruction *common = commonRemTransforms(I))
3136 return common;
3137
Dale Johannesened6af242009-01-21 00:35:19 +00003138 // 0 % X == 0 for integer, we don't need to preserve faults!
3139 if (Constant *LHS = dyn_cast<Constant>(Op0))
3140 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003142
Chris Lattner857e8cd2004-12-12 21:48:58 +00003143 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003144 // X % 0 == undef, we don't need to preserve faults!
3145 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003146 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003147
Chris Lattnera2881962003-02-18 19:28:33 +00003148 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003150
Chris Lattner97943922006-02-28 05:49:21 +00003151 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3152 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3153 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3154 return R;
3155 } else if (isa<PHINode>(Op0I)) {
3156 if (Instruction *NV = FoldOpIntoPhi(I))
3157 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003158 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003159
3160 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003161 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003162 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Chris Lattnera2881962003-02-18 19:28:33 +00003164 }
3165
Reid Spencer0a783f72006-11-02 01:53:59 +00003166 return 0;
3167}
3168
3169Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172 if (Instruction *common = commonIRemTransforms(I))
3173 return common;
3174
3175 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176 // X urem C^2 -> X and C
3177 // Check to see if this is an unsigned remainder with an exact power of 2,
3178 // if so, convert to a bitwise and.
3179 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003180 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003181 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003182 }
3183
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003184 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003185 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3186 if (RHSI->getOpcode() == Instruction::Shl &&
3187 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003188 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003189 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003190 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003191 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003192 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003193 }
3194 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003196
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3198 // where C1&C2 are powers of two.
3199 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3200 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3201 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3202 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003203 if ((STO->getValue().isPowerOf2()) &&
3204 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003205 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003206 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3207 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003208 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003209 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3210 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003211 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 }
3213 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003214 }
3215
Chris Lattner3f5b8772002-05-06 16:14:14 +00003216 return 0;
3217}
3218
Reid Spencer0a783f72006-11-02 01:53:59 +00003219Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
Dan Gohmancff55092007-11-05 23:16:33 +00003222 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003223 if (Instruction *common = commonIRemTransforms(I))
3224 return common;
3225
Owen Andersond672ecb2009-07-03 00:17:18 +00003226 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003227 if (!isa<Constant>(RHSNeg) ||
3228 (isa<ConstantInt>(RHSNeg) &&
3229 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 // X % -Y -> X % Y
3231 AddUsesToWorkList(I);
3232 I.setOperand(1, RHSNeg);
3233 return &I;
3234 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003235
Dan Gohmancff55092007-11-05 23:16:33 +00003236 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003238 if (I.getType()->isInteger()) {
3239 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3240 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3241 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003242 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003243 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 }
3245
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003246 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003247 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3248 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003249
Nick Lewycky9dce8732008-12-20 16:48:00 +00003250 bool hasNegative = false;
3251 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3252 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3253 if (RHS->getValue().isNegative())
3254 hasNegative = true;
3255
3256 if (hasNegative) {
3257 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003258 for (unsigned i = 0; i != VWidth; ++i) {
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3260 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003261 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003262 else
3263 Elts[i] = RHS;
3264 }
3265 }
3266
Owen Andersonaf7ec972009-07-28 21:19:26 +00003267 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003268 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003269 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 I.setOperand(1, NewRHSV);
3271 return &I;
3272 }
3273 }
3274 }
3275
Reid Spencer0a783f72006-11-02 01:53:59 +00003276 return 0;
3277}
3278
3279Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003280 return commonRemTransforms(I);
3281}
3282
Chris Lattner457dd822004-06-09 07:59:58 +00003283// isOneBitSet - Return true if there is exactly one bit set in the specified
3284// constant.
3285static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003286 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003287}
3288
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003289// isHighOnes - Return true if the constant is of the form 1+0+.
3290// This is the same as lowones(~X).
3291static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003292 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003293}
3294
Reid Spencere4d87aa2006-12-23 06:05:41 +00003295/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003296/// are carefully arranged to allow folding of expressions such as:
3297///
3298/// (A < B) | (A > B) --> (A != B)
3299///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003300/// Note that this is only valid if the first and second predicates have the
3301/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003302///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003303/// Three bits are used to represent the condition, as follows:
3304/// 0 A > B
3305/// 1 A == B
3306/// 2 A < B
3307///
3308/// <=> Value Definition
3309/// 000 0 Always false
3310/// 001 1 A > B
3311/// 010 2 A == B
3312/// 011 3 A >= B
3313/// 100 4 A < B
3314/// 101 5 A != B
3315/// 110 6 A <= B
3316/// 111 7 Always true
3317///
3318static unsigned getICmpCode(const ICmpInst *ICI) {
3319 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003320 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_UGT: return 1; // 001
3322 case ICmpInst::ICMP_SGT: return 1; // 001
3323 case ICmpInst::ICMP_EQ: return 2; // 010
3324 case ICmpInst::ICMP_UGE: return 3; // 011
3325 case ICmpInst::ICMP_SGE: return 3; // 011
3326 case ICmpInst::ICMP_ULT: return 4; // 100
3327 case ICmpInst::ICMP_SLT: return 4; // 100
3328 case ICmpInst::ICMP_NE: return 5; // 101
3329 case ICmpInst::ICMP_ULE: return 6; // 110
3330 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003331 // True -> 7
3332 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003333 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334 return 0;
3335 }
3336}
3337
Evan Cheng8db90722008-10-14 17:15:11 +00003338/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3339/// predicate into a three bit mask. It also returns whether it is an ordered
3340/// predicate by reference.
3341static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3342 isOrdered = false;
3343 switch (CC) {
3344 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3345 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003346 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3347 case FCmpInst::FCMP_UGT: return 1; // 001
3348 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3349 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003350 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3351 case FCmpInst::FCMP_UGE: return 3; // 011
3352 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3353 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003354 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3355 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003356 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3357 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003358 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003359 default:
3360 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003361 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003362 return 0;
3363 }
3364}
3365
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366/// getICmpValue - This is the complement of getICmpCode, which turns an
3367/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003368/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003369/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003370static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003371 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003373 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003374 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003375 case 1:
3376 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003377 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 else
Owen Anderson333c4002009-07-09 23:48:35 +00003379 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3380 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 case 3:
3382 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 else
Owen Anderson333c4002009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 case 4:
3387 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003388 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 else
Owen Anderson333c4002009-07-09 23:48:35 +00003390 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3391 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 case 6:
3393 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003394 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 else
Owen Anderson333c4002009-07-09 23:48:35 +00003396 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003397 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003398 }
3399}
3400
Evan Cheng8db90722008-10-14 17:15:11 +00003401/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3402/// opcode and two operands into either a FCmp instruction. isordered is passed
3403/// in to determine which kind of predicate to use in the new fcmp instruction.
3404static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003405 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003406 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003407 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003408 case 0:
3409 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003413 case 1:
3414 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003416 else
Owen Anderson333c4002009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003418 case 2:
3419 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003421 else
Owen Anderson333c4002009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003423 case 3:
3424 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003426 else
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 case 4:
3429 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003431 else
Owen Anderson333c4002009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 case 5:
3434 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003436 else
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003438 case 6:
3439 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003441 else
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003443 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003444 }
3445}
3446
Chris Lattnerb9553d62008-11-16 04:55:20 +00003447/// PredicatesFoldable - Return true if both predicates match sign or if at
3448/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3450 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003451 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3452 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453}
3454
3455namespace {
3456// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3457struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003458 InstCombiner &IC;
3459 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 ICmpInst::Predicate pred;
3461 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3462 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3463 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003464 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3466 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003467 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3468 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003469 return false;
3470 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003471 Instruction *apply(Instruction &Log) const {
3472 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3473 if (ICI->getOperand(0) != LHS) {
3474 assert(ICI->getOperand(1) == LHS);
3475 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 }
3477
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003478 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003480 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 unsigned Code;
3482 switch (Log.getOpcode()) {
3483 case Instruction::And: Code = LHSCode & RHSCode; break;
3484 case Instruction::Or: Code = LHSCode | RHSCode; break;
3485 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003486 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 }
3488
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003489 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3490 ICmpInst::isSignedPredicate(ICI->getPredicate());
3491
Owen Andersond672ecb2009-07-03 00:17:18 +00003492 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003493 if (Instruction *I = dyn_cast<Instruction>(RV))
3494 return I;
3495 // Otherwise, it's a constant boolean value...
3496 return IC.ReplaceInstUsesWith(Log, RV);
3497 }
3498};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003499} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003500
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3502// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003503// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003504Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003505 ConstantInt *OpRHS,
3506 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003507 BinaryOperator &TheAnd) {
3508 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003509 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003510 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003511 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003512
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513 switch (Op->getOpcode()) {
3514 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003515 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003517 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003519 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003520 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 }
3522 break;
3523 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003524 if (Together == AndRHS) // (X | C) & C --> C
3525 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003526
Chris Lattner6e7ba452005-01-01 16:22:27 +00003527 if (Op->hasOneUse() && Together != OpRHS) {
3528 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003529 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003530 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003531 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003533 }
3534 break;
3535 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003536 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // Adding a one to a single bit bit-field should be turned into an XOR
3538 // of the bit. First thing to check is to see if this AND is with a
3539 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003540 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541
3542 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003543 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Ok, at this point, we know that we are masking the result of the
3545 // ADD down to exactly one bit. If the constant we are adding has
3546 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003547 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003548
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Check to see if any bits below the one bit set in AndRHSV are set.
3550 if ((AddRHS & (AndRHSV-1)) == 0) {
3551 // If not, the only thing that can effect the output of the AND is
3552 // the bit specified by AndRHSV. If that bit is set, the effect of
3553 // the XOR is to toggle the bit. If it is clear, then the ADD has
3554 // no effect.
3555 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556 TheAnd.setOperand(0, X);
3557 return &TheAnd;
3558 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003562 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003563 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 }
3565 }
3566 }
3567 }
3568 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003569
3570 case Instruction::Shl: {
3571 // We know that the AND will not produce any of the bits shifted in, so if
3572 // the anded constant includes them, clear them now!
3573 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003575 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003577 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003578
Zhou Sheng290bec52007-03-29 08:15:12 +00003579 if (CI->getValue() == ShlMask) {
3580 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003581 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3582 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003583 TheAnd.setOperand(1, CI);
3584 return &TheAnd;
3585 }
3586 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003587 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003588 case Instruction::LShr:
3589 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003590 // We know that the AND will not produce any of the bits shifted in, so if
3591 // the anded constant includes them, clear them now! This only applies to
3592 // unsigned shifts, because a signed shr may bring in set bits!
3593 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003595 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003597 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003598
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 if (CI->getValue() == ShrMask) {
3600 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003601 return ReplaceInstUsesWith(TheAnd, Op);
3602 } else if (CI != AndRHS) {
3603 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3604 return &TheAnd;
3605 }
3606 break;
3607 }
3608 case Instruction::AShr:
3609 // Signed shr.
3610 // See if this is shifting in some sign extension, then masking it out
3611 // with an and.
3612 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003614 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003615 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003616 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003617 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003618 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003619 // Make the argument unsigned.
3620 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003621 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003622 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003623 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003624 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003625 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003626 }
3627 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003628 }
3629 return 0;
3630}
3631
Chris Lattner8b170942002-08-09 23:47:40 +00003632
Chris Lattnera96879a2004-09-29 17:40:11 +00003633/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3634/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3636/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003637/// insert new instructions.
3638Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 bool isSigned, bool Inside,
3640 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003641 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003642 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003643 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 if (Inside) {
3646 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003647 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003648
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003650 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003651 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003653 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 }
3655
3656 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003657 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003658 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003659 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003660 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003661 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003662 }
3663
3664 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003665 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003666
Reid Spencere4e40032007-03-21 23:19:50 +00003667 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003668 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003669 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 ICmpInst::Predicate pred = (isSigned ?
3671 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003672 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003674
Reid Spencere4e40032007-03-21 23:19:50 +00003675 // Emit V-Lo >u Hi-1-Lo
3676 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003677 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003678 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003680 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003681 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003682}
3683
Chris Lattner7203e152005-09-18 07:22:02 +00003684// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3685// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3686// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3687// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003688static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003689 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003690 uint32_t BitWidth = Val->getType()->getBitWidth();
3691 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003692
3693 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003694 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003695 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003696 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003697 return true;
3698}
3699
Chris Lattner7203e152005-09-18 07:22:02 +00003700/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3701/// where isSub determines whether the operator is a sub. If we can fold one of
3702/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003703///
3704/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3705/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3706/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707///
3708/// return (A +/- B).
3709///
3710Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003711 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003712 Instruction &I) {
3713 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3714 if (!LHSI || LHSI->getNumOperands() != 2 ||
3715 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3716
3717 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3718
3719 switch (LHSI->getOpcode()) {
3720 default: return 0;
3721 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003722 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003723 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003724 if ((Mask->getValue().countLeadingZeros() +
3725 Mask->getValue().countPopulation()) ==
3726 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003727 break;
3728
3729 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3730 // part, we don't need any explicit masks to take them out of A. If that
3731 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003732 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003733 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003734 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003735 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003736 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003737 break;
3738 }
3739 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740 return 0;
3741 case Instruction::Or:
3742 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003743 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003744 if ((Mask->getValue().countLeadingZeros() +
3745 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003746 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747 break;
3748 return 0;
3749 }
3750
3751 Instruction *New;
3752 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003753 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003755 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 return InsertNewInstBefore(New, I);
3757}
3758
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003759/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3760Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3761 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003762 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003763 ConstantInt *LHSCst, *RHSCst;
3764 ICmpInst::Predicate LHSCC, RHSCC;
3765
Chris Lattnerea065fb2008-11-16 05:10:52 +00003766 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003767 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3768 m_ConstantInt(LHSCst)), *Context) ||
3769 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3770 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003771 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003772
3773 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774 // where C is a power of 2
3775 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776 LHSCst->getValue().isPowerOf2()) {
3777 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003779 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003780 }
3781
3782 // From here on, we only handle:
3783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784 if (Val != Val2) return 0;
3785
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791 return 0;
3792
3793 // We can't fold (ugt x, C) & (sgt x, C2).
3794 if (!PredicatesFoldable(LHSCC, RHSCC))
3795 return 0;
3796
3797 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003798 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 if (ICmpInst::isSignedPredicate(LHSCC) ||
3800 (ICmpInst::isEquality(LHSCC) &&
3801 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003802 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805
3806 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 std::swap(LHS, RHS);
3808 std::swap(LHSCst, RHSCst);
3809 std::swap(LHSCC, RHSCC);
3810 }
3811
3812 // At this point, we know we have have two icmp instructions
3813 // comparing a value against two constants and and'ing the result
3814 // together. Because of the above check, we know that we only have
3815 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3816 // (from the FoldICmpLogical check above), that the two constants
3817 // are not equal and that the larger constant is on the RHS
3818 assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003821 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 case ICmpInst::ICMP_EQ:
3823 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003824 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3826 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3827 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003828 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003829 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3830 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3831 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3832 return ReplaceInstUsesWith(I, LHS);
3833 }
3834 case ICmpInst::ICMP_NE:
3835 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003836 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003838 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003839 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 break; // (X != 13 & X u< 15) -> no change
3841 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003842 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003843 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 break; // (X != 13 & X s< 15) -> no change
3845 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3846 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3847 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3848 return ReplaceInstUsesWith(I, RHS);
3849 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003850 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003851 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003852 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853 Val->getName()+".off");
3854 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003855 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003856 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003857 }
3858 break; // (X != 13 & X != 15) -> no change
3859 }
3860 break;
3861 case ICmpInst::ICMP_ULT:
3862 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003863 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003864 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3865 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003866 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003867 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3868 break;
3869 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3870 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3871 return ReplaceInstUsesWith(I, LHS);
3872 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3873 break;
3874 }
3875 break;
3876 case ICmpInst::ICMP_SLT:
3877 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003878 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003879 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3880 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003881 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3883 break;
3884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3886 return ReplaceInstUsesWith(I, LHS);
3887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3888 break;
3889 }
3890 break;
3891 case ICmpInst::ICMP_UGT:
3892 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003893 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003894 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3896 return ReplaceInstUsesWith(I, RHS);
3897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3898 break;
3899 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003901 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003904 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3905 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3907 break;
3908 }
3909 break;
3910 case ICmpInst::ICMP_SGT:
3911 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3914 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3915 return ReplaceInstUsesWith(I, RHS);
3916 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003919 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003920 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003921 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003922 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003923 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3924 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3926 break;
3927 }
3928 break;
3929 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930
3931 return 0;
3932}
3933
Chris Lattner42d1be02009-07-23 05:14:02 +00003934Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3935 FCmpInst *RHS) {
3936
3937 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3938 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3939 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3940 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3941 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3942 // If either of the constants are nans, then the whole thing returns
3943 // false.
3944 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003945 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003946 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3947 LHS->getOperand(0), RHS->getOperand(0));
3948 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003949
3950 // Handle vector zeros. This occurs because the canonical form of
3951 // "fcmp ord x,x" is "fcmp ord x, 0".
3952 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3953 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3954 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3955 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003956 return 0;
3957 }
3958
3959 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3960 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3961 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3962
3963
3964 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3965 // Swap RHS operands to match LHS.
3966 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3967 std::swap(Op1LHS, Op1RHS);
3968 }
3969
3970 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3971 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3972 if (Op0CC == Op1CC)
3973 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3974
3975 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003976 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003977 if (Op0CC == FCmpInst::FCMP_TRUE)
3978 return ReplaceInstUsesWith(I, RHS);
3979 if (Op1CC == FCmpInst::FCMP_TRUE)
3980 return ReplaceInstUsesWith(I, LHS);
3981
3982 bool Op0Ordered;
3983 bool Op1Ordered;
3984 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3985 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3986 if (Op1Pred == 0) {
3987 std::swap(LHS, RHS);
3988 std::swap(Op0Pred, Op1Pred);
3989 std::swap(Op0Ordered, Op1Ordered);
3990 }
3991 if (Op0Pred == 0) {
3992 // uno && ueq -> uno && (uno || eq) -> ueq
3993 // ord && olt -> ord && (ord && lt) -> olt
3994 if (Op0Ordered == Op1Ordered)
3995 return ReplaceInstUsesWith(I, RHS);
3996
3997 // uno && oeq -> uno && (ord && eq) -> false
3998 // uno && ord -> false
3999 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004000 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004001 // ord && ueq -> ord && (uno || eq) -> oeq
4002 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4003 Op0LHS, Op0RHS, Context));
4004 }
4005 }
4006
4007 return 0;
4008}
4009
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004010
Chris Lattner7e708292002-06-25 16:13:24 +00004011Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004012 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004014
Chris Lattnere87597f2004-10-16 18:11:37 +00004015 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004017
Chris Lattner6e7ba452005-01-01 16:22:27 +00004018 // and X, X = X
4019 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004020 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004021
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004022 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004023 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004024 if (SimplifyDemandedInstructionBits(I))
4025 return &I;
4026 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004027 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004028 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004029 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004030 } else if (isa<ConstantAggregateZero>(Op1)) {
4031 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004032 }
4033 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004034
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004035 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004036 const APInt& AndRHSMask = AndRHS->getValue();
4037 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004038
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004039 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004040 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004041 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004042 Value *Op0LHS = Op0I->getOperand(0);
4043 Value *Op0RHS = Op0I->getOperand(1);
4044 switch (Op0I->getOpcode()) {
4045 case Instruction::Xor:
4046 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004047 // If the mask is only needed on one incoming arm, push it up.
4048 if (Op0I->hasOneUse()) {
4049 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4050 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004051 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004052 Op0RHS->getName()+".masked");
4053 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004054 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004055 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004056 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004057 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004058 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4059 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004060 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004061 Op0LHS->getName()+".masked");
4062 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004063 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004064 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4065 }
4066 }
4067
Chris Lattner6e7ba452005-01-01 16:22:27 +00004068 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004069 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004070 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4071 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4072 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4073 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004074 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004075 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004077 break;
4078
4079 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004080 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4081 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4082 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4083 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004084 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004085
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004086 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4087 // has 1's for all bits that the subtraction with A might affect.
4088 if (Op0I->hasOneUse()) {
4089 uint32_t BitWidth = AndRHSMask.getBitWidth();
4090 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4091 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4092
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004093 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004094 if (!(A && A->isZero()) && // avoid infinite recursion.
4095 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004096 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004097 InsertNewInstBefore(NewNeg, I);
4098 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4099 }
4100 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004101 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004102
4103 case Instruction::Shl:
4104 case Instruction::LShr:
4105 // (1 << x) & 1 --> zext(x == 0)
4106 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004107 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004108 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004109 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004110 InsertNewInstBefore(NewICmp, I);
4111 return new ZExtInst(NewICmp, I.getType());
4112 }
4113 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 }
4115
Chris Lattner58403262003-07-23 19:25:52 +00004116 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004117 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004118 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004119 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004120 // If this is an integer truncation or change from signed-to-unsigned, and
4121 // if the source is an and/or with immediate, transform it. This
4122 // frequently occurs for bitfield accesses.
4123 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004125 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004126 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004127 if (CastOp->getOpcode() == Instruction::And) {
4128 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004129 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4130 // This will fold the two constants together, which may allow
4131 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004132 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004133 CastOp->getOperand(0), I.getType(),
4134 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004135 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004136 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004137 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004138 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4139 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004140 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004141 } else if (CastOp->getOpcode() == Instruction::Or) {
4142 // Change: and (cast (or X, C1) to T), C2
4143 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004144 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004145 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4146 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004147 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004148 return ReplaceInstUsesWith(I, AndRHS);
4149 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004150 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004151 }
Chris Lattner06782f82003-07-23 19:36:21 +00004152 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004153
4154 // Try to fold constant and into select arguments.
4155 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004156 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004157 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004158 if (isa<PHINode>(Op0))
4159 if (Instruction *NV = FoldOpIntoPhi(I))
4160 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004161 }
4162
Owen Andersond672ecb2009-07-03 00:17:18 +00004163 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4164 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004165
Chris Lattner5b62aa72004-06-18 06:07:51 +00004166 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004168
Misha Brukmancb6267b2004-07-30 12:50:08 +00004169 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004170 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004171 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004172 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004173 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004174 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004175 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004176
4177 {
Chris Lattner003b6202007-06-15 05:58:24 +00004178 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004179 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004180 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4181 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004182
4183 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004184 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004185 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004186 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004187 }
4188 }
4189
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004190 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004191 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4192 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004193
4194 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004195 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004196 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004197 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004198 }
4199 }
Chris Lattner64daab52006-04-01 08:03:55 +00004200
4201 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004202 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004203 if (A == Op1) { // (A^B)&A -> A&(A^B)
4204 I.swapOperands(); // Simplify below
4205 std::swap(Op0, Op1);
4206 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4207 cast<BinaryOperator>(Op0)->swapOperands();
4208 I.swapOperands(); // Simplify below
4209 std::swap(Op0, Op1);
4210 }
4211 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004212
Chris Lattner64daab52006-04-01 08:03:55 +00004213 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004214 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004215 if (B == Op0) { // B&(A^B) -> B&(B^A)
4216 cast<BinaryOperator>(Op1)->swapOperands();
4217 std::swap(A, B);
4218 }
4219 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004220 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004221 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004222 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004223 }
4224 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004225
4226 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004227 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4228 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004229 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004230 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4231 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004232 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004233 }
4234
Reid Spencere4d87aa2006-12-23 06:05:41 +00004235 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4236 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004237 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004238 return R;
4239
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004240 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4241 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4242 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004243 }
4244
Chris Lattner6fc205f2006-05-05 06:39:07 +00004245 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004246 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4247 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4248 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4249 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004250 if (SrcTy == Op1C->getOperand(0)->getType() &&
4251 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004252 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004253 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4254 I.getType(), TD) &&
4255 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4256 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004257 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004258 Op1C->getOperand(0),
4259 I.getName());
4260 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004261 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004262 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004263 }
Chris Lattnere511b742006-11-14 07:46:50 +00004264
4265 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004266 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4267 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4268 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004269 SI0->getOperand(1) == SI1->getOperand(1) &&
4270 (SI0->hasOneUse() || SI1->hasOneUse())) {
4271 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004272 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004273 SI1->getOperand(0),
4274 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004275 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004276 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004277 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004278 }
4279
Evan Cheng8db90722008-10-14 17:15:11 +00004280 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004281 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004282 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4283 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4284 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004285 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004286
Chris Lattner7e708292002-06-25 16:13:24 +00004287 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004288}
4289
Chris Lattner8c34cd22008-10-05 02:13:19 +00004290/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4291/// capable of providing pieces of a bswap. The subexpression provides pieces
4292/// of a bswap if it is proven that each of the non-zero bytes in the output of
4293/// the expression came from the corresponding "byte swapped" byte in some other
4294/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4295/// we know that the expression deposits the low byte of %X into the high byte
4296/// of the bswap result and that all other bytes are zero. This expression is
4297/// accepted, the high byte of ByteValues is set to X to indicate a correct
4298/// match.
4299///
4300/// This function returns true if the match was unsuccessful and false if so.
4301/// On entry to the function the "OverallLeftShift" is a signed integer value
4302/// indicating the number of bytes that the subexpression is later shifted. For
4303/// example, if the expression is later right shifted by 16 bits, the
4304/// OverallLeftShift value would be -2 on entry. This is used to specify which
4305/// byte of ByteValues is actually being set.
4306///
4307/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4308/// byte is masked to zero by a user. For example, in (X & 255), X will be
4309/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4310/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4311/// always in the local (OverallLeftShift) coordinate space.
4312///
4313static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4314 SmallVector<Value*, 8> &ByteValues) {
4315 if (Instruction *I = dyn_cast<Instruction>(V)) {
4316 // If this is an or instruction, it may be an inner node of the bswap.
4317 if (I->getOpcode() == Instruction::Or) {
4318 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4319 ByteValues) ||
4320 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4321 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004322 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004323
4324 // If this is a logical shift by a constant multiple of 8, recurse with
4325 // OverallLeftShift and ByteMask adjusted.
4326 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4327 unsigned ShAmt =
4328 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4329 // Ensure the shift amount is defined and of a byte value.
4330 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4331 return true;
4332
4333 unsigned ByteShift = ShAmt >> 3;
4334 if (I->getOpcode() == Instruction::Shl) {
4335 // X << 2 -> collect(X, +2)
4336 OverallLeftShift += ByteShift;
4337 ByteMask >>= ByteShift;
4338 } else {
4339 // X >>u 2 -> collect(X, -2)
4340 OverallLeftShift -= ByteShift;
4341 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004342 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004343 }
4344
4345 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4346 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4347
4348 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4349 ByteValues);
4350 }
4351
4352 // If this is a logical 'and' with a mask that clears bytes, clear the
4353 // corresponding bytes in ByteMask.
4354 if (I->getOpcode() == Instruction::And &&
4355 isa<ConstantInt>(I->getOperand(1))) {
4356 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4357 unsigned NumBytes = ByteValues.size();
4358 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4359 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4360
4361 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4362 // If this byte is masked out by a later operation, we don't care what
4363 // the and mask is.
4364 if ((ByteMask & (1 << i)) == 0)
4365 continue;
4366
4367 // If the AndMask is all zeros for this byte, clear the bit.
4368 APInt MaskB = AndMask & Byte;
4369 if (MaskB == 0) {
4370 ByteMask &= ~(1U << i);
4371 continue;
4372 }
4373
4374 // If the AndMask is not all ones for this byte, it's not a bytezap.
4375 if (MaskB != Byte)
4376 return true;
4377
4378 // Otherwise, this byte is kept.
4379 }
4380
4381 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4382 ByteValues);
4383 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004384 }
4385
Chris Lattner8c34cd22008-10-05 02:13:19 +00004386 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4387 // the input value to the bswap. Some observations: 1) if more than one byte
4388 // is demanded from this input, then it could not be successfully assembled
4389 // into a byteswap. At least one of the two bytes would not be aligned with
4390 // their ultimate destination.
4391 if (!isPowerOf2_32(ByteMask)) return true;
4392 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004393
Chris Lattner8c34cd22008-10-05 02:13:19 +00004394 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4395 // is demanded, it needs to go into byte 0 of the result. This means that the
4396 // byte needs to be shifted until it lands in the right byte bucket. The
4397 // shift amount depends on the position: if the byte is coming from the high
4398 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4399 // low part, it must be shifted left.
4400 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4401 if (InputByteNo < ByteValues.size()/2) {
4402 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4403 return true;
4404 } else {
4405 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4406 return true;
4407 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004408
4409 // If the destination byte value is already defined, the values are or'd
4410 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004411 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004412 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004413 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004414 return false;
4415}
4416
4417/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4418/// If so, insert the new bswap intrinsic and return it.
4419Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004420 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004421 if (!ITy || ITy->getBitWidth() % 16 ||
4422 // ByteMask only allows up to 32-byte values.
4423 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004424 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425
4426 /// ByteValues - For each byte of the result, we keep track of which value
4427 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004428 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004429 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430
4431 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004432 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4433 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004434 return 0;
4435
4436 // Check to see if all of the bytes come from the same value.
4437 Value *V = ByteValues[0];
4438 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4439
4440 // Check to make sure that all of the bytes come from the same value.
4441 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4442 if (ByteValues[i] != V)
4443 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004444 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004445 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004446 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004447 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004448}
4449
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004450/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4451/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4452/// we can simplify this expression to "cond ? C : D or B".
4453static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004454 Value *C, Value *D,
4455 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004456 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004457 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004458 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004459 return 0;
4460
Chris Lattnera6a474d2008-11-16 04:26:55 +00004461 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004462 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004463 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004464 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, B);
4466 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004467 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004468 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004469 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004470 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004471 return 0;
4472}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004473
Chris Lattner69d4ced2008-11-16 05:20:07 +00004474/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4475Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4476 ICmpInst *LHS, ICmpInst *RHS) {
4477 Value *Val, *Val2;
4478 ConstantInt *LHSCst, *RHSCst;
4479 ICmpInst::Predicate LHSCC, RHSCC;
4480
4481 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004482 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4483 m_ConstantInt(LHSCst)), *Context) ||
4484 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4485 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004486 return 0;
4487
4488 // From here on, we only handle:
4489 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4490 if (Val != Val2) return 0;
4491
4492 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4493 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4494 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4495 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4496 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4497 return 0;
4498
4499 // We can't fold (ugt x, C) | (sgt x, C2).
4500 if (!PredicatesFoldable(LHSCC, RHSCC))
4501 return 0;
4502
4503 // Ensure that the larger constant is on the RHS.
4504 bool ShouldSwap;
4505 if (ICmpInst::isSignedPredicate(LHSCC) ||
4506 (ICmpInst::isEquality(LHSCC) &&
4507 ICmpInst::isSignedPredicate(RHSCC)))
4508 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4509 else
4510 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4511
4512 if (ShouldSwap) {
4513 std::swap(LHS, RHS);
4514 std::swap(LHSCst, RHSCst);
4515 std::swap(LHSCC, RHSCC);
4516 }
4517
4518 // At this point, we know we have have two icmp instructions
4519 // comparing a value against two constants and or'ing the result
4520 // together. Because of the above check, we know that we only have
4521 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4522 // FoldICmpLogical check above), that the two constants are not
4523 // equal.
4524 assert(LHSCst != RHSCst && "Compares not folded above?");
4525
4526 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004527 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004528 case ICmpInst::ICMP_EQ:
4529 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004530 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004531 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004532 if (LHSCst == SubOne(RHSCst, Context)) {
4533 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004534 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004535 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4536 Val->getName()+".off");
4537 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00004538 AddCST = ConstantExpr::getSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004539 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004540 }
4541 break; // (X == 13 | X == 15) -> no change
4542 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4543 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4544 break;
4545 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4546 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4547 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4548 return ReplaceInstUsesWith(I, RHS);
4549 }
4550 break;
4551 case ICmpInst::ICMP_NE:
4552 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004553 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004554 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4555 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4556 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4557 return ReplaceInstUsesWith(I, LHS);
4558 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4559 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4560 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004561 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004562 }
4563 break;
4564 case ICmpInst::ICMP_ULT:
4565 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4568 break;
4569 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4570 // If RHSCst is [us]MAXINT, it is always false. Not handling
4571 // this can cause overflow.
4572 if (RHSCst->isMaxValue(false))
4573 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004574 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4575 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004576 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4577 break;
4578 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4579 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4580 return ReplaceInstUsesWith(I, RHS);
4581 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4582 break;
4583 }
4584 break;
4585 case ICmpInst::ICMP_SLT:
4586 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004587 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4589 break;
4590 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4591 // If RHSCst is [us]MAXINT, it is always false. Not handling
4592 // this can cause overflow.
4593 if (RHSCst->isMaxValue(true))
4594 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004595 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4596 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004597 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4598 break;
4599 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4600 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4601 return ReplaceInstUsesWith(I, RHS);
4602 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4603 break;
4604 }
4605 break;
4606 case ICmpInst::ICMP_UGT:
4607 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004608 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004609 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4610 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4611 return ReplaceInstUsesWith(I, LHS);
4612 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4613 break;
4614 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4615 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004616 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004617 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4618 break;
4619 }
4620 break;
4621 case ICmpInst::ICMP_SGT:
4622 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004623 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004624 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4625 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4626 return ReplaceInstUsesWith(I, LHS);
4627 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4628 break;
4629 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4630 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004631 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004632 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4633 break;
4634 }
4635 break;
4636 }
4637 return 0;
4638}
4639
Chris Lattner5414cc52009-07-23 05:46:22 +00004640Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4641 FCmpInst *RHS) {
4642 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4643 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4644 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4645 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4646 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4647 // If either of the constants are nans, then the whole thing returns
4648 // true.
4649 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004650 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004651
4652 // Otherwise, no need to compare the two constants, compare the
4653 // rest.
4654 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4655 LHS->getOperand(0), RHS->getOperand(0));
4656 }
4657
4658 // Handle vector zeros. This occurs because the canonical form of
4659 // "fcmp uno x,x" is "fcmp uno x, 0".
4660 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4661 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4662 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4663 LHS->getOperand(0), RHS->getOperand(0));
4664
4665 return 0;
4666 }
4667
4668 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4669 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4670 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4671
4672 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4673 // Swap RHS operands to match LHS.
4674 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4675 std::swap(Op1LHS, Op1RHS);
4676 }
4677 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4678 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4679 if (Op0CC == Op1CC)
4680 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4681 Op0LHS, Op0RHS);
4682 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004683 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004684 if (Op0CC == FCmpInst::FCMP_FALSE)
4685 return ReplaceInstUsesWith(I, RHS);
4686 if (Op1CC == FCmpInst::FCMP_FALSE)
4687 return ReplaceInstUsesWith(I, LHS);
4688 bool Op0Ordered;
4689 bool Op1Ordered;
4690 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4691 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4692 if (Op0Ordered == Op1Ordered) {
4693 // If both are ordered or unordered, return a new fcmp with
4694 // or'ed predicates.
4695 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4696 Op0LHS, Op0RHS, Context);
4697 if (Instruction *I = dyn_cast<Instruction>(RV))
4698 return I;
4699 // Otherwise, it's a constant boolean value...
4700 return ReplaceInstUsesWith(I, RV);
4701 }
4702 }
4703 return 0;
4704}
4705
Bill Wendlinga698a472008-12-01 08:23:25 +00004706/// FoldOrWithConstants - This helper function folds:
4707///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004708/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004709///
4710/// into:
4711///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004712/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004713///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004714/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004715Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004716 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004717 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4718 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004719
Bill Wendling286a0542008-12-02 06:24:20 +00004720 Value *V1 = 0;
4721 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004722 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004723
Bill Wendling29976b92008-12-02 06:18:11 +00004724 APInt Xor = CI1->getValue() ^ CI2->getValue();
4725 if (!Xor.isAllOnesValue()) return 0;
4726
Bill Wendling286a0542008-12-02 06:24:20 +00004727 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004728 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004729 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4730 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004731 }
4732
4733 return 0;
4734}
4735
Chris Lattner7e708292002-06-25 16:13:24 +00004736Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004737 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004738 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004739
Chris Lattner42593e62007-03-24 23:56:43 +00004740 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004741 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004742
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004743 // or X, X = X
4744 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004745 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004746
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004747 // See if we can simplify any instructions used by the instruction whose sole
4748 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004749 if (SimplifyDemandedInstructionBits(I))
4750 return &I;
4751 if (isa<VectorType>(I.getType())) {
4752 if (isa<ConstantAggregateZero>(Op1)) {
4753 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4754 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4755 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4756 return ReplaceInstUsesWith(I, I.getOperand(1));
4757 }
Chris Lattner42593e62007-03-24 23:56:43 +00004758 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004759
Chris Lattner3f5b8772002-05-06 16:14:14 +00004760 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004761 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004762 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004763 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004764 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4765 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004766 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004767 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004768 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004769 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004770 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004771 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004772
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004773 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004774 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4775 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004776 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004777 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004778 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004779 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004780 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004781 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004782
4783 // Try to fold constant and into select arguments.
4784 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004785 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004786 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004787 if (isa<PHINode>(Op0))
4788 if (Instruction *NV = FoldOpIntoPhi(I))
4789 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004790 }
4791
Chris Lattner4f637d42006-01-06 17:59:59 +00004792 Value *A = 0, *B = 0;
4793 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004794
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004795 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004796 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4797 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004798 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004799 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4800 return ReplaceInstUsesWith(I, Op0);
4801
Chris Lattner6423d4c2006-07-10 20:25:24 +00004802 // (A | B) | C and A | (B | C) -> bswap if possible.
4803 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4805 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4806 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4807 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004808 if (Instruction *BSwap = MatchBSwap(I))
4809 return BSwap;
4810 }
4811
Chris Lattner6e4c6492005-05-09 04:58:36 +00004812 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004813 if (Op0->hasOneUse() &&
4814 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004815 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004816 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004817 InsertNewInstBefore(NOr, I);
4818 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004819 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004820 }
4821
4822 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004823 if (Op1->hasOneUse() &&
4824 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004825 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004826 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004827 InsertNewInstBefore(NOr, I);
4828 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004829 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004830 }
4831
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004832 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004833 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004834 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4835 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004836 Value *V1 = 0, *V2 = 0, *V3 = 0;
4837 C1 = dyn_cast<ConstantInt>(C);
4838 C2 = dyn_cast<ConstantInt>(D);
4839 if (C1 && C2) { // (A & C1)|(B & C2)
4840 // If we have: ((V + N) & C1) | (V & C2)
4841 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4842 // replace with V+N.
4843 if (C1->getValue() == ~C2->getValue()) {
4844 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004846 // Add commutes, try both ways.
4847 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4848 return ReplaceInstUsesWith(I, A);
4849 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4850 return ReplaceInstUsesWith(I, A);
4851 }
4852 // Or commutes, try both ways.
4853 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004854 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004855 // Add commutes, try both ways.
4856 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4857 return ReplaceInstUsesWith(I, B);
4858 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4859 return ReplaceInstUsesWith(I, B);
4860 }
4861 }
Chris Lattner044e5332007-04-08 08:01:49 +00004862 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004863 }
4864
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004865 // Check to see if we have any common things being and'ed. If so, find the
4866 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004867 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4868 if (A == B) // (A & C)|(A & D) == A & (C|D)
4869 V1 = A, V2 = C, V3 = D;
4870 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4871 V1 = A, V2 = B, V3 = C;
4872 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4873 V1 = C, V2 = A, V3 = D;
4874 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4875 V1 = C, V2 = A, V3 = B;
4876
4877 if (V1) {
4878 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004879 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4880 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004881 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004882 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004883
Dan Gohman1975d032008-10-30 20:40:10 +00004884 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004885 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004886 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004887 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004888 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004889 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004890 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004891 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004892 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004893
Bill Wendlingb01865c2008-11-30 13:52:49 +00004894 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004895 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4896 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004897 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004898 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004899 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4900 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004901 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004902 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004903 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4904 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004905 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004906 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004907 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4908 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004909 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004910 }
Chris Lattnere511b742006-11-14 07:46:50 +00004911
4912 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004913 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4914 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4915 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004916 SI0->getOperand(1) == SI1->getOperand(1) &&
4917 (SI0->hasOneUse() || SI1->hasOneUse())) {
4918 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004919 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004920 SI1->getOperand(0),
4921 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004922 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004923 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004924 }
4925 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004926
Bill Wendlingb3833d12008-12-01 01:07:11 +00004927 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004928 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4929 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004930 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004931 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004932 }
4933 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004934 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4935 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004936 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004937 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004938 }
4939
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004940 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004941 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004942 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004943 } else {
4944 A = 0;
4945 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004946 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004947 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004948 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004949 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004950
Misha Brukmancb6267b2004-07-30 12:50:08 +00004951 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004952 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004953 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004954 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004955 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004956 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004957 }
Chris Lattnera2881962003-02-18 19:28:33 +00004958
Reid Spencere4d87aa2006-12-23 06:05:41 +00004959 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4960 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004961 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004962 return R;
4963
Chris Lattner69d4ced2008-11-16 05:20:07 +00004964 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4965 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4966 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004967 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004968
4969 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004970 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004971 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004972 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004973 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4974 !isa<ICmpInst>(Op1C->getOperand(0))) {
4975 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004976 if (SrcTy == Op1C->getOperand(0)->getType() &&
4977 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004978 // Only do this if the casts both really cause code to be
4979 // generated.
4980 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4981 I.getType(), TD) &&
4982 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4983 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004984 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004985 Op1C->getOperand(0),
4986 I.getName());
4987 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004988 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004989 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004990 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004991 }
Chris Lattner99c65742007-10-24 05:38:08 +00004992 }
4993
4994
4995 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4996 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004997 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4998 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4999 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005000 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005001
Chris Lattner7e708292002-06-25 16:13:24 +00005002 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005003}
5004
Dan Gohman844731a2008-05-13 00:00:25 +00005005namespace {
5006
Chris Lattnerc317d392004-02-16 01:20:27 +00005007// XorSelf - Implements: X ^ X --> 0
5008struct XorSelf {
5009 Value *RHS;
5010 XorSelf(Value *rhs) : RHS(rhs) {}
5011 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5012 Instruction *apply(BinaryOperator &Xor) const {
5013 return &Xor;
5014 }
5015};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005016
Dan Gohman844731a2008-05-13 00:00:25 +00005017}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005018
Chris Lattner7e708292002-06-25 16:13:24 +00005019Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005020 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005022
Evan Chengd34af782008-03-25 20:07:13 +00005023 if (isa<UndefValue>(Op1)) {
5024 if (isa<UndefValue>(Op0))
5025 // Handle undef ^ undef -> 0 special case. This is a common
5026 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005027 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005028 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005029 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005030
Chris Lattnerc317d392004-02-16 01:20:27 +00005031 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005032 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005033 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005034 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005035 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005036
5037 // See if we can simplify any instructions used by the instruction whose sole
5038 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005039 if (SimplifyDemandedInstructionBits(I))
5040 return &I;
5041 if (isa<VectorType>(I.getType()))
5042 if (isa<ConstantAggregateZero>(Op1))
5043 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005044
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005045 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005046 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005047 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5048 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5049 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5050 if (Op0I->getOpcode() == Instruction::And ||
5051 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005052 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5053 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005054 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005055 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005056 Op0I->getOperand(1)->getName()+".not");
5057 InsertNewInstBefore(NotY, I);
5058 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005059 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005060 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005061 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005062 }
5063 }
5064 }
5065 }
5066
5067
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005069 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005070 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005071 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005072 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005074
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005075 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005076 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005077 FCI->getOperand(0), FCI->getOperand(1));
5078 }
5079
Nick Lewycky517e1f52008-05-31 19:01:33 +00005080 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5081 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5082 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5083 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5084 Instruction::CastOps Opcode = Op0C->getOpcode();
5085 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005086 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005087 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005088 Op0C->getDestTy())) {
5089 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005090 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005091 CI->getOpcode(), CI->getInversePredicate(),
5092 CI->getOperand(0), CI->getOperand(1)), I);
5093 NewCI->takeName(CI);
5094 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5095 }
5096 }
5097 }
5098 }
5099 }
5100
Reid Spencere4d87aa2006-12-23 06:05:41 +00005101 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005102 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005103 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5104 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005105 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5106 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005107 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005108 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005109 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005110
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005112 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005113 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005114 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005115 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005116 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005117 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005118 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005119 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005120 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005121 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005122 Constant *C = ConstantInt::get(*Context,
5123 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005124 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005125
Chris Lattner7c4049c2004-01-12 19:35:11 +00005126 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005127 } else if (Op0I->getOpcode() == Instruction::Or) {
5128 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005129 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005130 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005131 // Anything in both C1 and C2 is known to be zero, remove it from
5132 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005133 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5134 NewRHS = ConstantExpr::getAnd(NewRHS,
5135 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005136 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005137 I.setOperand(0, Op0I->getOperand(0));
5138 I.setOperand(1, NewRHS);
5139 return &I;
5140 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005141 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005142 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005143 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005144
5145 // Try to fold constant and into select arguments.
5146 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005147 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005148 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005149 if (isa<PHINode>(Op0))
5150 if (Instruction *NV = FoldOpIntoPhi(I))
5151 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005152 }
5153
Owen Andersond672ecb2009-07-03 00:17:18 +00005154 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005155 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005156 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005157
Owen Andersond672ecb2009-07-03 00:17:18 +00005158 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005159 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005160 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005161
Chris Lattner318bf792007-03-18 22:51:34 +00005162
5163 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5164 if (Op1I) {
5165 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005166 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005167 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005168 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005169 I.swapOperands();
5170 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005171 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005172 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005173 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005174 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005175 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005176 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005177 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005178 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5180 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005181 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005182 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005183 std::swap(A, B);
5184 }
Chris Lattner318bf792007-03-18 22:51:34 +00005185 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005186 I.swapOperands(); // Simplified below.
5187 std::swap(Op0, Op1);
5188 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005189 }
Chris Lattner318bf792007-03-18 22:51:34 +00005190 }
5191
5192 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5193 if (Op0I) {
5194 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005195 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5196 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005197 if (A == Op1) // (B|A)^B == (A|B)^B
5198 std::swap(A, B);
5199 if (B == Op1) { // (A|B)^B == A & ~B
5200 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005201 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5202 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005203 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005204 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005205 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005206 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005207 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005208 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5210 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005211 if (A == Op1) // (A&B)^A -> (B&A)^A
5212 std::swap(A, B);
5213 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005214 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005215 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005216 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005217 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005218 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005219 }
Chris Lattner318bf792007-03-18 22:51:34 +00005220 }
5221
5222 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5223 if (Op0I && Op1I && Op0I->isShift() &&
5224 Op0I->getOpcode() == Op1I->getOpcode() &&
5225 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5226 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5227 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005228 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005229 Op1I->getOperand(0),
5230 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005231 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005232 Op1I->getOperand(1));
5233 }
5234
5235 if (Op0I && Op1I) {
5236 Value *A, *B, *C, *D;
5237 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005238 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5239 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005240 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005241 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005242 }
5243 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005244 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5245 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005246 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005247 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005248 }
5249
5250 // (A & B)^(C & D)
5251 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005252 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5253 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005254 // (X & Y)^(X & Y) -> (Y^Z) & X
5255 Value *X = 0, *Y = 0, *Z = 0;
5256 if (A == C)
5257 X = A, Y = B, Z = D;
5258 else if (A == D)
5259 X = A, Y = B, Z = C;
5260 else if (B == C)
5261 X = B, Y = A, Z = D;
5262 else if (B == D)
5263 X = B, Y = A, Z = C;
5264
5265 if (X) {
5266 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005267 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5268 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005269 }
5270 }
5271 }
5272
Reid Spencere4d87aa2006-12-23 06:05:41 +00005273 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5274 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005275 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005276 return R;
5277
Chris Lattner6fc205f2006-05-05 06:39:07 +00005278 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005279 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005280 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005281 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5282 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005283 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005284 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005285 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5286 I.getType(), TD) &&
5287 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5288 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005289 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005290 Op1C->getOperand(0),
5291 I.getName());
5292 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005293 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005294 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005295 }
Chris Lattner99c65742007-10-24 05:38:08 +00005296 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005297
Chris Lattner7e708292002-06-25 16:13:24 +00005298 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005299}
5300
Owen Andersond672ecb2009-07-03 00:17:18 +00005301static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005302 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005303 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005304}
Chris Lattnera96879a2004-09-29 17:40:11 +00005305
Dan Gohman6de29f82009-06-15 22:12:54 +00005306static bool HasAddOverflow(ConstantInt *Result,
5307 ConstantInt *In1, ConstantInt *In2,
5308 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005309 if (IsSigned)
5310 if (In2->getValue().isNegative())
5311 return Result->getValue().sgt(In1->getValue());
5312 else
5313 return Result->getValue().slt(In1->getValue());
5314 else
5315 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005316}
5317
Dan Gohman6de29f82009-06-15 22:12:54 +00005318/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005319/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005320static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005321 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005322 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005323 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005324
Dan Gohman6de29f82009-06-15 22:12:54 +00005325 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5326 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005327 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005328 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5329 ExtractElement(In1, Idx, Context),
5330 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005331 IsSigned))
5332 return true;
5333 }
5334 return false;
5335 }
5336
5337 return HasAddOverflow(cast<ConstantInt>(Result),
5338 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5339 IsSigned);
5340}
5341
5342static bool HasSubOverflow(ConstantInt *Result,
5343 ConstantInt *In1, ConstantInt *In2,
5344 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005345 if (IsSigned)
5346 if (In2->getValue().isNegative())
5347 return Result->getValue().slt(In1->getValue());
5348 else
5349 return Result->getValue().sgt(In1->getValue());
5350 else
5351 return Result->getValue().ugt(In1->getValue());
5352}
5353
Dan Gohman6de29f82009-06-15 22:12:54 +00005354/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5355/// overflowed for this type.
5356static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005357 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005358 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005359 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005360
5361 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5362 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005363 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005364 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5365 ExtractElement(In1, Idx, Context),
5366 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005367 IsSigned))
5368 return true;
5369 }
5370 return false;
5371 }
5372
5373 return HasSubOverflow(cast<ConstantInt>(Result),
5374 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5375 IsSigned);
5376}
5377
Chris Lattner574da9b2005-01-13 20:14:25 +00005378/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5379/// code necessary to compute the offset from the base pointer (without adding
5380/// in the base pointer). Return the result as a signed integer of intptr size.
5381static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005382 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005383 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005384 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005385 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005386 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005387
5388 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005389 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005390 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005391
Gabor Greif177dd3f2008-06-12 21:37:33 +00005392 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5393 ++i, ++GTI) {
5394 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005395 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005396 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5397 if (OpC->isZero()) continue;
5398
5399 // Handle a struct index, which adds its field offset to the pointer.
5400 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5401 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5402
5403 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005404 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005405 ConstantInt::get(*Context,
5406 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005407 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005409 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005410 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005411 GEP->getName()+".offs"), I);
5412 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005413 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005414
Owen Andersoneed707b2009-07-24 23:12:02 +00005415 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005416 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005417 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5418 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005420 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 else {
5422 // Emit an add instruction.
5423 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005424 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005426 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005428 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005429 // Convert to correct type.
5430 if (Op->getType() != IntPtrTy) {
5431 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005432 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005433 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005434 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5435 true,
5436 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005437 }
5438 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005439 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005440 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005441 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005442 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005443 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 GEP->getName()+".idx"), I);
5445 }
5446
5447 // Emit an add instruction.
5448 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005449 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005450 cast<Constant>(Result));
5451 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005452 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005453 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005454 }
5455 return Result;
5456}
5457
Chris Lattner10c0d912008-04-22 02:53:33 +00005458
Dan Gohman8f080f02009-07-17 22:16:21 +00005459/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5460/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5461/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5462/// be complex, and scales are involved. The above expression would also be
5463/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5464/// This later form is less amenable to optimization though, and we are allowed
5465/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005466///
5467/// If we can't emit an optimized form for this expression, this returns null.
5468///
5469static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5470 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005471 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005472 gep_type_iterator GTI = gep_type_begin(GEP);
5473
5474 // Check to see if this gep only has a single variable index. If so, and if
5475 // any constant indices are a multiple of its scale, then we can compute this
5476 // in terms of the scale of the variable index. For example, if the GEP
5477 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5478 // because the expression will cross zero at the same point.
5479 unsigned i, e = GEP->getNumOperands();
5480 int64_t Offset = 0;
5481 for (i = 1; i != e; ++i, ++GTI) {
5482 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5483 // Compute the aggregate offset of constant indices.
5484 if (CI->isZero()) continue;
5485
5486 // Handle a struct index, which adds its field offset to the pointer.
5487 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5488 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5489 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005490 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005491 Offset += Size*CI->getSExtValue();
5492 }
5493 } else {
5494 // Found our variable index.
5495 break;
5496 }
5497 }
5498
5499 // If there are no variable indices, we must have a constant offset, just
5500 // evaluate it the general way.
5501 if (i == e) return 0;
5502
5503 Value *VariableIdx = GEP->getOperand(i);
5504 // Determine the scale factor of the variable element. For example, this is
5505 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005506 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005507
5508 // Verify that there are no other variable indices. If so, emit the hard way.
5509 for (++i, ++GTI; i != e; ++i, ++GTI) {
5510 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5511 if (!CI) return 0;
5512
5513 // Compute the aggregate offset of constant indices.
5514 if (CI->isZero()) continue;
5515
5516 // Handle a struct index, which adds its field offset to the pointer.
5517 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5518 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5519 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005520 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005521 Offset += Size*CI->getSExtValue();
5522 }
5523 }
5524
5525 // Okay, we know we have a single variable index, which must be a
5526 // pointer/array/vector index. If there is no offset, life is simple, return
5527 // the index.
5528 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5529 if (Offset == 0) {
5530 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5531 // we don't need to bother extending: the extension won't affect where the
5532 // computation crosses zero.
5533 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5534 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005535 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005536 return VariableIdx;
5537 }
5538
5539 // Otherwise, there is an index. The computation we will do will be modulo
5540 // the pointer size, so get it.
5541 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5542
5543 Offset &= PtrSizeMask;
5544 VariableScale &= PtrSizeMask;
5545
5546 // To do this transformation, any constant index must be a multiple of the
5547 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5548 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5549 // multiple of the variable scale.
5550 int64_t NewOffs = Offset / (int64_t)VariableScale;
5551 if (Offset != NewOffs*(int64_t)VariableScale)
5552 return 0;
5553
5554 // Okay, we can do this evaluation. Start by converting the index to intptr.
5555 const Type *IntPtrTy = TD.getIntPtrType();
5556 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005557 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005558 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005559 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005560 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005561 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005562}
5563
5564
Reid Spencere4d87aa2006-12-23 06:05:41 +00005565/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005566/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005567Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005568 ICmpInst::Predicate Cond,
5569 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005570 // Look through bitcasts.
5571 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5572 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005573
Chris Lattner574da9b2005-01-13 20:14:25 +00005574 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005575 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005576 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005577 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005578 // know pointers can't overflow since the gep is inbounds. See if we can
5579 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005580 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5581
5582 // If not, synthesize the offset the hard way.
5583 if (Offset == 0)
5584 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005585 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005586 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005587 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005588 // If the base pointers are different, but the indices are the same, just
5589 // compare the base pointer.
5590 if (PtrBase != GEPRHS->getOperand(0)) {
5591 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005592 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005593 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005594 if (IndicesTheSame)
5595 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5596 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5597 IndicesTheSame = false;
5598 break;
5599 }
5600
5601 // If all indices are the same, just compare the base pointers.
5602 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005603 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005604 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005605
5606 // Otherwise, the base pointers are different and the indices are
5607 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005608 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005609 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005610
Chris Lattnere9d782b2005-01-13 22:25:21 +00005611 // If one of the GEPs has all zero indices, recurse.
5612 bool AllZeros = true;
5613 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5614 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5615 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5616 AllZeros = false;
5617 break;
5618 }
5619 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005620 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5621 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005622
5623 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005624 AllZeros = true;
5625 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5626 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5627 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5628 AllZeros = false;
5629 break;
5630 }
5631 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005632 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005633
Chris Lattner4401c9c2005-01-14 00:20:05 +00005634 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5635 // If the GEPs only differ by one index, compare it.
5636 unsigned NumDifferences = 0; // Keep track of # differences.
5637 unsigned DiffOperand = 0; // The operand that differs.
5638 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5639 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005640 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5641 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005642 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005643 NumDifferences = 2;
5644 break;
5645 } else {
5646 if (NumDifferences++) break;
5647 DiffOperand = i;
5648 }
5649 }
5650
5651 if (NumDifferences == 0) // SAME GEP?
5652 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneed707b2009-07-24 23:12:02 +00005653 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005654 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005655
Chris Lattner4401c9c2005-01-14 00:20:05 +00005656 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005657 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5658 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005659 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005660 return new ICmpInst(*Context,
5661 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005662 }
5663 }
5664
Reid Spencere4d87aa2006-12-23 06:05:41 +00005665 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005666 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005667 if (TD &&
5668 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005669 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5670 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5671 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5672 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005673 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005674 }
5675 }
5676 return 0;
5677}
5678
Chris Lattnera5406232008-05-19 20:18:56 +00005679/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5680///
5681Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5682 Instruction *LHSI,
5683 Constant *RHSC) {
5684 if (!isa<ConstantFP>(RHSC)) return 0;
5685 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5686
5687 // Get the width of the mantissa. We don't want to hack on conversions that
5688 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005689 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005690 if (MantissaWidth == -1) return 0; // Unknown.
5691
5692 // Check to see that the input is converted from an integer type that is small
5693 // enough that preserves all bits. TODO: check here for "known" sign bits.
5694 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005695 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005696
5697 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5699 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005700 ++InputSize;
5701
5702 // If the conversion would lose info, don't hack on this.
5703 if ((int)InputSize > MantissaWidth)
5704 return 0;
5705
5706 // Otherwise, we can potentially simplify the comparison. We know that it
5707 // will always come through as an integer value and we know the constant is
5708 // not a NAN (it would have been previously simplified).
5709 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5710
5711 ICmpInst::Predicate Pred;
5712 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005713 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005714 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005715 case FCmpInst::FCMP_OEQ:
5716 Pred = ICmpInst::ICMP_EQ;
5717 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005718 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005719 case FCmpInst::FCMP_OGT:
5720 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5721 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005723 case FCmpInst::FCMP_OGE:
5724 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5725 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005726 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005727 case FCmpInst::FCMP_OLT:
5728 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5729 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005730 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005731 case FCmpInst::FCMP_OLE:
5732 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5733 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005735 case FCmpInst::FCMP_ONE:
5736 Pred = ICmpInst::ICMP_NE;
5737 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005738 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005741 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005742 }
5743
5744 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5745
5746 // Now we know that the APFloat is a normal number, zero or inf.
5747
Chris Lattner85162782008-05-20 03:50:52 +00005748 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005749 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005750 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005751
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005752 if (!LHSUnsigned) {
5753 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5754 // and large values.
5755 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5756 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5757 APFloat::rmNearestTiesToEven);
5758 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5759 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5760 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005761 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5762 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005763 }
5764 } else {
5765 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5766 // +INF and large values.
5767 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5768 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5769 APFloat::rmNearestTiesToEven);
5770 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5771 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5772 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005773 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5774 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005775 }
Chris Lattnera5406232008-05-19 20:18:56 +00005776 }
5777
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005778 if (!LHSUnsigned) {
5779 // See if the RHS value is < SignedMin.
5780 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5781 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5782 APFloat::rmNearestTiesToEven);
5783 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5784 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5785 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005786 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5787 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005788 }
Chris Lattnera5406232008-05-19 20:18:56 +00005789 }
5790
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005791 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5792 // [0, UMAX], but it may still be fractional. See if it is fractional by
5793 // casting the FP value to the integer value and back, checking for equality.
5794 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005795 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005796 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5797 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005798 if (!RHS.isZero()) {
5799 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005800 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5801 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005802 if (!Equal) {
5803 // If we had a comparison against a fractional value, we have to adjust
5804 // the compare predicate and sometimes the value. RHSC is rounded towards
5805 // zero at this point.
5806 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005807 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005808 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005809 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005810 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005811 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 case ICmpInst::ICMP_ULE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> false
5815 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005816 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005817 break;
5818 case ICmpInst::ICMP_SLE:
5819 // (float)int <= 4.4 --> int <= 4
5820 // (float)int <= -4.4 --> int < -4
5821 if (RHS.isNegative())
5822 Pred = ICmpInst::ICMP_SLT;
5823 break;
5824 case ICmpInst::ICMP_ULT:
5825 // (float)int < -4.4 --> false
5826 // (float)int < 4.4 --> int <= 4
5827 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005828 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005829 Pred = ICmpInst::ICMP_ULE;
5830 break;
5831 case ICmpInst::ICMP_SLT:
5832 // (float)int < -4.4 --> int < -4
5833 // (float)int < 4.4 --> int <= 4
5834 if (!RHS.isNegative())
5835 Pred = ICmpInst::ICMP_SLE;
5836 break;
5837 case ICmpInst::ICMP_UGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> true
5840 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005841 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005842 break;
5843 case ICmpInst::ICMP_SGT:
5844 // (float)int > 4.4 --> int > 4
5845 // (float)int > -4.4 --> int >= -4
5846 if (RHS.isNegative())
5847 Pred = ICmpInst::ICMP_SGE;
5848 break;
5849 case ICmpInst::ICMP_UGE:
5850 // (float)int >= -4.4 --> true
5851 // (float)int >= 4.4 --> int > 4
5852 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005853 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005854 Pred = ICmpInst::ICMP_UGT;
5855 break;
5856 case ICmpInst::ICMP_SGE:
5857 // (float)int >= -4.4 --> int >= -4
5858 // (float)int >= 4.4 --> int > 4
5859 if (!RHS.isNegative())
5860 Pred = ICmpInst::ICMP_SGT;
5861 break;
5862 }
Chris Lattnera5406232008-05-19 20:18:56 +00005863 }
5864 }
5865
5866 // Lower this FP comparison into an appropriate integer version of the
5867 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005868 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005869}
5870
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5872 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005874
Chris Lattner58e97462007-01-14 19:42:17 +00005875 // Fold trivial predicates.
5876 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005877 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005878 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005879 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005880
5881 // Simplify 'fcmp pred X, X'
5882 if (Op0 == Op1) {
5883 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005884 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005885 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5886 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5887 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005889 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5890 case FCmpInst::FCMP_OLT: // True if ordered and less than
5891 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005892 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005893
5894 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5895 case FCmpInst::FCMP_ULT: // True if unordered or less than
5896 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5897 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5898 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5899 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005900 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005901 return &I;
5902
5903 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5904 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5905 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5906 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5907 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5908 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005909 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005910 return &I;
5911 }
5912 }
5913
Reid Spencere4d87aa2006-12-23 06:05:41 +00005914 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005915 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005916
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 // Handle fcmp with constant RHS
5918 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005919 // If the constant is a nan, see if we can fold the comparison based on it.
5920 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5921 if (CFP->getValueAPF().isNaN()) {
5922 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005923 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005924 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5925 "Comparison must be either ordered or unordered!");
5926 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005927 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005928 }
5929 }
5930
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5932 switch (LHSI->getOpcode()) {
5933 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005934 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5935 // block. If in the same block, we're encouraging jump threading. If
5936 // not, we are just pessimizing the code by making an i1 phi.
5937 if (LHSI->getParent() == I.getParent())
5938 if (Instruction *NV = FoldOpIntoPhi(I))
5939 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005941 case Instruction::SIToFP:
5942 case Instruction::UIToFP:
5943 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5944 return NV;
5945 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 case Instruction::Select:
5947 // If either operand of the select is a constant, we can fold the
5948 // comparison into the select arms, which will cause one to be
5949 // constant folded and the select turned into a bitwise or.
5950 Value *Op1 = 0, *Op2 = 0;
5951 if (LHSI->hasOneUse()) {
5952 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5953 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005954 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005956 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957 LHSI->getOperand(2), RHSC,
5958 I.getName()), I);
5959 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5960 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005961 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005963 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 LHSI->getOperand(1), RHSC,
5965 I.getName()), I);
5966 }
5967 }
5968
5969 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005970 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 break;
5972 }
5973 }
5974
5975 return Changed ? &I : 0;
5976}
5977
5978Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5979 bool Changed = SimplifyCompare(I);
5980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5981 const Type *Ty = Op0->getType();
5982
5983 // icmp X, X
5984 if (Op0 == Op1)
Owen Andersoneed707b2009-07-24 23:12:02 +00005985 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005986 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005987
5988 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005989 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005990
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005992 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005993 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5994 isa<ConstantPointerNull>(Op0)) &&
5995 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005996 isa<ConstantPointerNull>(Op1)))
Owen Andersoneed707b2009-07-24 23:12:02 +00005997 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005998 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005999
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006001 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006002 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006003 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006004 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006005 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006006 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006007 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006008 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006010 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006011
Reid Spencere4d87aa2006-12-23 06:05:41 +00006012 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006013 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006014 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006015 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006016 Instruction *Not = BinaryOperator::CreateNot(*Context,
6017 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006018 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006019 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006020 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_SGT:
6022 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006023 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006024 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006025 Instruction *Not = BinaryOperator::CreateNot(*Context,
6026 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 InsertNewInstBefore(Not, I);
6028 return BinaryOperator::CreateAnd(Not, Op0);
6029 }
6030 case ICmpInst::ICMP_UGE:
6031 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006034 Instruction *Not = BinaryOperator::CreateNot(*Context,
6035 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006036 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006037 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006038 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006039 case ICmpInst::ICMP_SGE:
6040 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6041 // FALL THROUGH
6042 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006043 Instruction *Not = BinaryOperator::CreateNot(*Context,
6044 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006045 InsertNewInstBefore(Not, I);
6046 return BinaryOperator::CreateOr(Not, Op0);
6047 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006048 }
Chris Lattner8b170942002-08-09 23:47:40 +00006049 }
6050
Dan Gohman1c8491e2009-04-25 17:12:48 +00006051 unsigned BitWidth = 0;
6052 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006053 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6054 else if (Ty->isIntOrIntVector())
6055 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006056
6057 bool isSignBit = false;
6058
Dan Gohman81b28ce2008-09-16 18:46:06 +00006059 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006060 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006061 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006062
Chris Lattnerb6566012008-01-05 01:18:20 +00006063 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6064 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006065 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006066 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006067 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006068 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006069
Dan Gohman81b28ce2008-09-16 18:46:06 +00006070 // If we have an icmp le or icmp ge instruction, turn it into the
6071 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6072 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006073 switch (I.getPredicate()) {
6074 default: break;
6075 case ICmpInst::ICMP_ULE:
6076 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006077 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6079 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SLE:
6081 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006082 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6084 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_UGE:
6086 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006087 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006088 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6089 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006090 case ICmpInst::ICMP_SGE:
6091 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006092 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006093 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6094 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006095 }
6096
Chris Lattner183661e2008-07-11 05:40:05 +00006097 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006098 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006099 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6101 }
6102
6103 // See if we can fold the comparison based on range information we can get
6104 // by checking whether bits are known to be zero or one in the input.
6105 if (BitWidth != 0) {
6106 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6107 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6108
6109 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006110 isSignBit ? APInt::getSignBit(BitWidth)
6111 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006113 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 if (SimplifyDemandedBits(I.getOperandUse(1),
6115 APInt::getAllOnesValue(BitWidth),
6116 Op1KnownZero, Op1KnownOne, 0))
6117 return &I;
6118
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006119 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006120 // in. Compute the Min, Max and RHS values based on the known bits. For the
6121 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6123 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6124 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6125 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126 Op0Min, Op0Max);
6127 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128 Op1Min, Op1Max);
6129 } else {
6130 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131 Op0Min, Op0Max);
6132 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6133 Op1Min, Op1Max);
6134 }
6135
Chris Lattner183661e2008-07-11 05:40:05 +00006136 // If Min and Max are known to be the same, then SimplifyDemandedBits
6137 // figured out that the LHS is a constant. Just constant fold this now so
6138 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006140 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006141 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006143 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006144 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145
Chris Lattner183661e2008-07-11 05:40:05 +00006146 // Based on the range information we know about the LHS, see if we can
6147 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006149 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006150 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006152 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006153 break;
6154 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006156 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006162 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006164 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006167 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6168 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169
6170 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6171 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006172 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006173 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 }
Chris Lattner84dff672008-07-11 05:08:55 +00006175 break;
6176 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006178 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006180 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181
6182 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006183 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188
6189 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6190 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006192 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 }
Chris Lattner84dff672008-07-11 05:08:55 +00006194 break;
6195 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006197 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006201 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6203 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006204 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6205 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 }
Chris Lattner84dff672008-07-11 05:08:55 +00006207 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 case ICmpInst::ICMP_SGT:
6209 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006210 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006212 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213
6214 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006215 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6217 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006218 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6219 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006220 }
6221 break;
6222 case ICmpInst::ICMP_SGE:
6223 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6224 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006227 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006228 break;
6229 case ICmpInst::ICMP_SLE:
6230 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6231 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006232 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006234 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235 break;
6236 case ICmpInst::ICMP_UGE:
6237 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6238 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006239 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006241 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006242 break;
6243 case ICmpInst::ICMP_ULE:
6244 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6245 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006246 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006247 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006248 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006249 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006250 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251
6252 // Turn a signed comparison into an unsigned one if both operands
6253 // are known to have the same sign.
6254 if (I.isSignedPredicate() &&
6255 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6256 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006257 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006258 }
6259
6260 // Test if the ICmpInst instruction is used exclusively by a select as
6261 // part of a minimum or maximum operation. If so, refrain from doing
6262 // any other folding. This helps out other analyses which understand
6263 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6264 // and CodeGen. And in this case, at least one of the comparison
6265 // operands has at least one user besides the compare (the select),
6266 // which would often largely negate the benefit of folding anyway.
6267 if (I.hasOneUse())
6268 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6269 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6270 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6271 return 0;
6272
6273 // See if we are doing a comparison between a constant and an instruction that
6274 // can be folded into the comparison.
6275 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006276 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006277 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006279 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006280 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6281 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006282 }
6283
Chris Lattner01deb9d2007-04-03 17:43:25 +00006284 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006285 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6286 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006288 case Instruction::GetElementPtr:
6289 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006290 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 bool isAllZeros = true;
6292 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6293 if (!isa<Constant>(LHSI->getOperand(i)) ||
6294 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6295 isAllZeros = false;
6296 break;
6297 }
6298 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006299 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006300 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006301 }
6302 break;
6303
Chris Lattner6970b662005-04-23 15:31:55 +00006304 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006305 // Only fold icmp into the PHI if the phi and fcmp are in the same
6306 // block. If in the same block, we're encouraging jump threading. If
6307 // not, we are just pessimizing the code by making an i1 phi.
6308 if (LHSI->getParent() == I.getParent())
6309 if (Instruction *NV = FoldOpIntoPhi(I))
6310 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006311 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006312 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006313 // If either operand of the select is a constant, we can fold the
6314 // comparison into the select arms, which will cause one to be
6315 // constant folded and the select turned into a bitwise or.
6316 Value *Op1 = 0, *Op2 = 0;
6317 if (LHSI->hasOneUse()) {
6318 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6319 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006320 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006322 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 LHSI->getOperand(2), RHSC,
6324 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006325 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6326 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006327 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006329 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 LHSI->getOperand(1), RHSC,
6331 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006332 }
6333 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006334
Chris Lattner6970b662005-04-23 15:31:55 +00006335 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006336 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006337 break;
6338 }
Chris Lattner4802d902007-04-06 18:57:34 +00006339 case Instruction::Malloc:
6340 // If we have (malloc != null), and if the malloc has a single use, we
6341 // can assume it is successful and remove the malloc.
6342 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6343 AddToWorkList(LHSI);
Owen Andersoneed707b2009-07-24 23:12:02 +00006344 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006345 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006346 }
6347 break;
6348 }
Chris Lattner6970b662005-04-23 15:31:55 +00006349 }
6350
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006352 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006353 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006354 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006355 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6357 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006358 return NI;
6359
Reid Spencere4d87aa2006-12-23 06:05:41 +00006360 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006361 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6362 // now.
6363 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6364 if (isa<PointerType>(Op0->getType()) &&
6365 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006366 // We keep moving the cast from the left operand over to the right
6367 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006368 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006369
Chris Lattner57d86372007-01-06 01:45:59 +00006370 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6371 // so eliminate it as well.
6372 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6373 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006374
Chris Lattnerde90b762003-11-03 04:25:02 +00006375 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006376 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006377 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006378 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006379 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006381 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006382 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006383 }
Owen Anderson333c4002009-07-09 23:48:35 +00006384 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006385 }
Chris Lattner57d86372007-01-06 01:45:59 +00006386 }
6387
6388 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006389 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006390 // This comes up when you have code like
6391 // int X = A < B;
6392 // if (X) ...
6393 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006394 // with a constant or another cast from the same type.
6395 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006396 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006397 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006398 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006399
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006400 // See if it's the same type of instruction on the left and right.
6401 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6402 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006403 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006404 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006405 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006406 default: break;
6407 case Instruction::Add:
6408 case Instruction::Sub:
6409 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006410 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006411 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006412 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006413 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6414 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6415 if (CI->getValue().isSignBit()) {
6416 ICmpInst::Predicate Pred = I.isSignedPredicate()
6417 ? I.getUnsignedPredicate()
6418 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006419 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006420 Op1I->getOperand(0));
6421 }
6422
6423 if (CI->getValue().isMaxSignedValue()) {
6424 ICmpInst::Predicate Pred = I.isSignedPredicate()
6425 ? I.getUnsignedPredicate()
6426 : I.getSignedPredicate();
6427 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006428 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006429 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006430 }
6431 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006432 break;
6433 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006434 if (!I.isEquality())
6435 break;
6436
Nick Lewycky5d52c452008-08-21 05:56:10 +00006437 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6438 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6439 // Mask = -1 >> count-trailing-zeros(Cst).
6440 if (!CI->isZero() && !CI->isOne()) {
6441 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006442 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006443 APInt::getLowBitsSet(AP.getBitWidth(),
6444 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006445 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006446 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6447 Mask);
6448 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6449 Mask);
6450 InsertNewInstBefore(And1, I);
6451 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006452 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006453 }
6454 }
6455 break;
6456 }
6457 }
6458 }
6459 }
6460
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006461 // ~x < ~y --> y < x
6462 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006463 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6464 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006465 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006466 }
6467
Chris Lattner65b72ba2006-09-18 04:22:48 +00006468 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006469 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006470
6471 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006472 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6473 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006474 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006475
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006476 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006477 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6478 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006479 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006480 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006481 }
6482
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006483 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006485 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006486 if (match(B, m_ConstantInt(C1), *Context) &&
6487 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006488 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006489 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006490 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006491 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006492 InsertNewInstBefore(Xor, I));
6493 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006494
6495 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006496 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6497 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6498 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6499 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006500 }
6501 }
6502
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006503 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006504 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006505 // A == (A^B) -> B == 0
6506 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006507 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006508 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006509 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006510
6511 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006512 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006513 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006514 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006515
6516 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006517 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006518 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006519 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006520
Chris Lattner9c2328e2006-11-14 06:06:06 +00006521 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6522 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006523 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6524 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006525 Value *X = 0, *Y = 0, *Z = 0;
6526
6527 if (A == C) {
6528 X = B; Y = D; Z = A;
6529 } else if (A == D) {
6530 X = B; Y = C; Z = A;
6531 } else if (B == C) {
6532 X = A; Y = D; Z = B;
6533 } else if (B == D) {
6534 X = A; Y = C; Z = B;
6535 }
6536
6537 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006538 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6539 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006540 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006541 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006542 return &I;
6543 }
6544 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006545 }
Chris Lattner7e708292002-06-25 16:13:24 +00006546 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006547}
6548
Chris Lattner562ef782007-06-20 23:46:26 +00006549
6550/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6551/// and CmpRHS are both known to be integer constants.
6552Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6553 ConstantInt *DivRHS) {
6554 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6555 const APInt &CmpRHSV = CmpRHS->getValue();
6556
6557 // FIXME: If the operand types don't match the type of the divide
6558 // then don't attempt this transform. The code below doesn't have the
6559 // logic to deal with a signed divide and an unsigned compare (and
6560 // vice versa). This is because (x /s C1) <s C2 produces different
6561 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6562 // (x /u C1) <u C2. Simply casting the operands and result won't
6563 // work. :( The if statement below tests that condition and bails
6564 // if it finds it.
6565 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6566 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6567 return 0;
6568 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006570 if (DivIsSigned && DivRHS->isAllOnesValue())
6571 return 0; // The overflow computation also screws up here
6572 if (DivRHS->isOne())
6573 return 0; // Not worth bothering, and eliminates some funny cases
6574 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006575
6576 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6577 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6578 // C2 (CI). By solving for X we can turn this into a range check
6579 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006580 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006581
6582 // Determine if the product overflows by seeing if the product is
6583 // not equal to the divide. Make sure we do the same kind of divide
6584 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006585 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6586 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006587
6588 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006590
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 // Figure out the interval that is being checked. For example, a comparison
6592 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6593 // Compute this interval based on the constants involved and the signedness of
6594 // the compare/divide. This computes a half-open interval, keeping track of
6595 // whether either value in the interval overflows. After analysis each
6596 // overflow variable is set to 0 if it's corresponding bound variable is valid
6597 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6598 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006599 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600
Chris Lattner562ef782007-06-20 23:46:26 +00006601 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006603 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 HiOverflow = LoOverflow = ProdOV;
6605 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006606 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006607 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006608 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006610 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS,
Owen Andersond672ecb2009-07-03 00:17:18 +00006611 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006612 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006613 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006614 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6615 HiOverflow = LoOverflow = ProdOV;
6616 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006617 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006618 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006621 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6622 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006623 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006624 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006625 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006626 true) ? -1 : 0;
6627 }
Chris Lattner562ef782007-06-20 23:46:26 +00006628 }
Dan Gohman76491272008-02-13 22:09:18 +00006629 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006630 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006632 LoBound = AddOne(DivRHS, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006633 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006634 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6635 HiOverflow = 1; // [INTMIN+1, overflow)
6636 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6637 }
Dan Gohman76491272008-02-13 22:09:18 +00006638 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006640 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006641 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006642 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006643 LoOverflow = AddWithOverflow(LoBound, HiBound,
6644 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006645 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006646 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6647 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006648 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006649 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006650 }
6651
Chris Lattner1dbfd482007-06-21 18:11:19 +00006652 // Dividing by a negative swaps the condition. LT <-> GT
6653 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006654 }
6655
6656 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006658 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006659 case ICmpInst::ICMP_EQ:
6660 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006661 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006662 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006663 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006664 ICmpInst::ICMP_UGE, X, LoBound);
6665 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006667 ICmpInst::ICMP_ULT, X, HiBound);
6668 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006670 case ICmpInst::ICMP_NE:
6671 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006672 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006673 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006674 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006675 ICmpInst::ICMP_ULT, X, LoBound);
6676 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006678 ICmpInst::ICMP_UGE, X, HiBound);
6679 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006680 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006681 case ICmpInst::ICMP_ULT:
6682 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006683 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006684 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006685 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006686 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006687 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006688 case ICmpInst::ICMP_UGT:
6689 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006690 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006691 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006692 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006693 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006695 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006696 else
Owen Anderson333c4002009-07-09 23:48:35 +00006697 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006698 }
6699}
6700
6701
Chris Lattner01deb9d2007-04-03 17:43:25 +00006702/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6703///
6704Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6705 Instruction *LHSI,
6706 ConstantInt *RHS) {
6707 const APInt &RHSV = RHS->getValue();
6708
6709 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006710 case Instruction::Trunc:
6711 if (ICI.isEquality() && LHSI->hasOneUse()) {
6712 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6713 // of the high bits truncated out of x are known.
6714 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6715 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6716 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6717 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6718 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6719
6720 // If all the high bits are known, we can do this xform.
6721 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6722 // Pull in the high bits from known-ones set.
6723 APInt NewRHS(RHS->getValue());
6724 NewRHS.zext(SrcBits);
6725 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006726 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006727 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006728 }
6729 }
6730 break;
6731
Duncan Sands0091bf22007-04-04 06:42:45 +00006732 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006733 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6734 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6735 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006736 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6737 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006738 Value *CompareVal = LHSI->getOperand(0);
6739
6740 // If the sign bit of the XorCST is not set, there is no change to
6741 // the operation, just stop using the Xor.
6742 if (!XorCST->getValue().isNegative()) {
6743 ICI.setOperand(0, CompareVal);
6744 AddToWorkList(LHSI);
6745 return &ICI;
6746 }
6747
6748 // Was the old condition true if the operand is positive?
6749 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6750
6751 // If so, the new one isn't.
6752 isTrueIfPositive ^= true;
6753
6754 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006755 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006756 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 else
Owen Anderson333c4002009-07-09 23:48:35 +00006758 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006759 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006760 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006761
6762 if (LHSI->hasOneUse()) {
6763 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6764 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6765 const APInt &SignBit = XorCST->getValue();
6766 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767 ? ICI.getUnsignedPredicate()
6768 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006769 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006770 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006771 }
6772
6773 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006774 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006775 const APInt &NotSignBit = XorCST->getValue();
6776 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6777 ? ICI.getUnsignedPredicate()
6778 : ICI.getSignedPredicate();
6779 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006780 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006781 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006782 }
6783 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006784 }
6785 break;
6786 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6787 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6788 LHSI->getOperand(0)->hasOneUse()) {
6789 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6790
6791 // If the LHS is an AND of a truncating cast, we can widen the
6792 // and/compare to be the input width without changing the value
6793 // produced, eliminating a cast.
6794 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6795 // We can do this transformation if either the AND constant does not
6796 // have its sign bit set or if it is an equality comparison.
6797 // Extending a relational comparison when we're checking the sign
6798 // bit would not work.
6799 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006800 (ICI.isEquality() ||
6801 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006802 uint32_t BitWidth =
6803 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6804 APInt NewCST = AndCST->getValue();
6805 NewCST.zext(BitWidth);
6806 APInt NewCI = RHSV;
6807 NewCI.zext(BitWidth);
6808 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006809 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006810 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006811 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006812 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006813 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006814 }
6815 }
6816
6817 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6818 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6819 // happens a LOT in code produced by the C front-end, for bitfield
6820 // access.
6821 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6822 if (Shift && !Shift->isShift())
6823 Shift = 0;
6824
6825 ConstantInt *ShAmt;
6826 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6827 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6828 const Type *AndTy = AndCST->getType(); // Type of the and.
6829
6830 // We can fold this as long as we can't shift unknown bits
6831 // into the mask. This can only happen with signed shift
6832 // rights, as they sign-extend.
6833 if (ShAmt) {
6834 bool CanFold = Shift->isLogicalShift();
6835 if (!CanFold) {
6836 // To test for the bad case of the signed shr, see if any
6837 // of the bits shifted in could be tested after the mask.
6838 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6839 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6840
6841 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6842 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6843 AndCST->getValue()) == 0)
6844 CanFold = true;
6845 }
6846
6847 if (CanFold) {
6848 Constant *NewCst;
6849 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006850 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006851 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006852 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006853
6854 // Check to see if we are shifting out any of the bits being
6855 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006856 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006857 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 // If we shifted bits out, the fold is not going to work out.
6859 // As a special case, check to see if this means that the
6860 // result is always true or false now.
6861 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006862 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006864 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865 } else {
6866 ICI.setOperand(1, NewCst);
6867 Constant *NewAndCST;
6868 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006869 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006871 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006872 LHSI->setOperand(1, NewAndCST);
6873 LHSI->setOperand(0, Shift->getOperand(0));
6874 AddToWorkList(Shift); // Shift is dead.
6875 AddUsesToWorkList(ICI);
6876 return &ICI;
6877 }
6878 }
6879 }
6880
6881 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6882 // preferable because it allows the C<<Y expression to be hoisted out
6883 // of a loop if Y is invariant and X is not.
6884 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006885 ICI.isEquality() && !Shift->isArithmeticShift() &&
6886 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006887 // Compute C << Y.
6888 Value *NS;
6889 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006890 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006891 Shift->getOperand(1), "tmp");
6892 } else {
6893 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006894 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006895 Shift->getOperand(1), "tmp");
6896 }
6897 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6898
6899 // Compute X & (C << Y).
6900 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006901 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006902 InsertNewInstBefore(NewAnd, ICI);
6903
6904 ICI.setOperand(0, NewAnd);
6905 return &ICI;
6906 }
6907 }
6908 break;
6909
Chris Lattnera0141b92007-07-15 20:42:37 +00006910 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6911 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6912 if (!ShAmt) break;
6913
6914 uint32_t TypeBits = RHSV.getBitWidth();
6915
6916 // Check that the shift amount is in range. If not, don't perform
6917 // undefined shifts. When the shift is visited it will be
6918 // simplified.
6919 if (ShAmt->uge(TypeBits))
6920 break;
6921
6922 if (ICI.isEquality()) {
6923 // If we are comparing against bits always shifted out, the
6924 // comparison cannot succeed.
6925 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006926 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006927 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006928 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6929 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006930 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006931 return ReplaceInstUsesWith(ICI, Cst);
6932 }
6933
6934 if (LHSI->hasOneUse()) {
6935 // Otherwise strength reduce the shift into an and.
6936 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6937 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006938 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006939 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006940
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006942 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 Mask, LHSI->getName()+".mask");
6944 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006945 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006946 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006947 }
6948 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006949
6950 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6951 bool TrueIfSigned = false;
6952 if (LHSI->hasOneUse() &&
6953 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6954 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006955 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006956 (TypeBits-ShAmt->getZExtValue()-1));
6957 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006958 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006959 Mask, LHSI->getName()+".mask");
6960 Value *And = InsertNewInstBefore(AndI, ICI);
6961
Owen Anderson333c4002009-07-09 23:48:35 +00006962 return new ICmpInst(*Context,
6963 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006964 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006965 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006966 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006967 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006968
6969 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006970 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006971 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006972 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006973 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006974
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006975 // Check that the shift amount is in range. If not, don't perform
6976 // undefined shifts. When the shift is visited it will be
6977 // simplified.
6978 uint32_t TypeBits = RHSV.getBitWidth();
6979 if (ShAmt->uge(TypeBits))
6980 break;
6981
6982 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006983
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006984 // If we are comparing against bits always shifted out, the
6985 // comparison cannot succeed.
6986 APInt Comp = RHSV << ShAmtVal;
6987 if (LHSI->getOpcode() == Instruction::LShr)
6988 Comp = Comp.lshr(ShAmtVal);
6989 else
6990 Comp = Comp.ashr(ShAmtVal);
6991
6992 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6993 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006994 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006995 return ReplaceInstUsesWith(ICI, Cst);
6996 }
6997
6998 // Otherwise, check to see if the bits shifted out are known to be zero.
6999 // If so, we can compare against the unshifted value:
7000 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007001 if (LHSI->hasOneUse() &&
7002 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007003 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007004 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007005 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007006 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007007
Evan Chengf30752c2008-04-23 00:38:06 +00007008 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 // Otherwise strength reduce the shift into an and.
7010 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007011 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007012
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007013 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007014 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007015 Mask, LHSI->getName()+".mask");
7016 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007017 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007018 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019 }
7020 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007021 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007022
7023 case Instruction::SDiv:
7024 case Instruction::UDiv:
7025 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026 // Fold this div into the comparison, producing a range check.
7027 // Determine, based on the divide type, what the range is being
7028 // checked. If there is an overflow on the low or high side, remember
7029 // it, otherwise compute the range [low, hi) bounding the new value.
7030 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007031 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033 DivRHS))
7034 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007035 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007036
7037 case Instruction::Add:
7038 // Fold: icmp pred (add, X, C1), C2
7039
7040 if (!ICI.isEquality()) {
7041 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042 if (!LHSC) break;
7043 const APInt &LHSV = LHSC->getValue();
7044
7045 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046 .subtract(LHSV);
7047
7048 if (ICI.isSignedPredicate()) {
7049 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007050 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007051 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007052 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007053 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007054 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007055 }
7056 } else {
7057 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007058 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007059 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007060 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007061 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007062 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007063 }
7064 }
7065 }
7066 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 }
7068
7069 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070 if (ICI.isEquality()) {
7071 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072
7073 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7074 // the second operand is a constant, simplify a bit.
7075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076 switch (BO->getOpcode()) {
7077 case Instruction::SRem:
7078 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7082 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007083 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007084 BO->getName());
7085 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007086 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007087 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088 }
7089 }
7090 break;
7091 case Instruction::Add:
7092 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7093 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7094 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007095 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007096 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 } else if (RHSV == 0) {
7098 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7099 // efficiently invertible, or if the add has just this one use.
7100 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7101
Owen Andersond672ecb2009-07-03 00:17:18 +00007102 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007103 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007104 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007105 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007106 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007107 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 InsertNewInstBefore(Neg, ICI);
7109 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007110 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 }
7112 }
7113 break;
7114 case Instruction::Xor:
7115 // For the xor case, we can xor two constants together, eliminating
7116 // the explicit xor.
7117 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007118 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007119 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 // FALLTHROUGH
7122 case Instruction::Sub:
7123 // Replace (([sub|xor] A, B) != 0) with (A != B)
7124 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007125 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126 BO->getOperand(1));
7127 break;
7128
7129 case Instruction::Or:
7130 // If bits are being or'd in that are not present in the constant we
7131 // are comparing against, then the comparison could never succeed!
7132 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007133 Constant *NotCI = ConstantExpr::getNot(RHS);
7134 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007135 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007136 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007137 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007138 }
7139 break;
7140
7141 case Instruction::And:
7142 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143 // If bits are being compared against that are and'd out, then the
7144 // comparison can never succeed!
7145 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007146 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007147 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007148 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149
7150 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007152 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007154 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155
7156 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007157 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007159 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007162 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007163 }
7164
7165 // ((X & ~7) == 0) --> X < 8
7166 if (RHSV == 0 && isHighOnes(BOC)) {
7167 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007168 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007171 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172 }
7173 }
7174 default: break;
7175 }
7176 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177 // Handle icmp {eq|ne} <intrinsic>, intcst.
7178 if (II->getIntrinsicID() == Intrinsic::bswap) {
7179 AddToWorkList(II);
7180 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007181 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182 return &ICI;
7183 }
7184 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185 }
7186 return 0;
7187}
7188
7189/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190/// We only handle extending casts so far.
7191///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007192Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007194 Value *LHSCIOp = LHSCI->getOperand(0);
7195 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007197 Value *RHSCIOp;
7198
Chris Lattner8c756c12007-05-05 22:41:33 +00007199 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7200 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007201 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007203 cast<IntegerType>(DestTy)->getBitWidth()) {
7204 Value *RHSOp = 0;
7205 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007206 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007207 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208 RHSOp = RHSC->getOperand(0);
7209 // If the pointer types don't match, insert a bitcast.
7210 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007211 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007212 }
7213
7214 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007215 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007216 }
7217
7218 // The code below only handles extension cast instructions, so far.
7219 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007220 if (LHSCI->getOpcode() != Instruction::ZExt &&
7221 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007222 return 0;
7223
Reid Spencere4d87aa2006-12-23 06:05:41 +00007224 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007226
Reid Spencere4d87aa2006-12-23 06:05:41 +00007227 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007228 // Not an extension from the same type?
7229 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007230 if (RHSCIOp->getType() != LHSCIOp->getType())
7231 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007232
Nick Lewycky4189a532008-01-28 03:48:02 +00007233 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007234 // and the other is a zext), then we can't handle this.
7235 if (CI->getOpcode() != LHSCI->getOpcode())
7236 return 0;
7237
Nick Lewycky4189a532008-01-28 03:48:02 +00007238 // Deal with equality cases early.
7239 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007240 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007241
7242 // A signed comparison of sign extended values simplifies into a
7243 // signed comparison.
7244 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007245 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007246
7247 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007248 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007249 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007250
Reid Spencere4d87aa2006-12-23 06:05:41 +00007251 // If we aren't dealing with a constant on the RHS, exit early
7252 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253 if (!CI)
7254 return 0;
7255
7256 // Compute the constant that would happen if we truncated to SrcTy then
7257 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007258 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7259 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007260 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261
7262 // If the re-extended constant didn't change...
7263 if (Res2 == CI) {
7264 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007266 // %A = sext i16 %X to i32
7267 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007269 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270 // because %A may have negative value.
7271 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007272 // However, we allow this when the compare is EQ/NE, because they are
7273 // signless.
7274 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007275 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007276 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277 }
7278
7279 // The re-extended constant changed so the constant cannot be represented
7280 // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282 // First, handle some easy cases. We know the result cannot be equal at this
7283 // point so handle the ICI.isEquality() cases
7284 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007285 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007287 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288
7289 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290 // should have been folded away previously and not enter in here.
7291 Value *Result;
7292 if (isSignedCmp) {
7293 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007294 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007295 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007297 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007298 } else {
7299 // We're performing an unsigned comparison.
7300 if (isSignedExt) {
7301 // We're performing an unsigned comp with a sign extended value.
7302 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007303 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007304 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7305 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007306 } else {
7307 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007308 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309 }
7310 }
7311
7312 // Finally, return the value computed.
7313 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007314 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007315 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007316
7317 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7318 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7319 "ICmp should be folded!");
7320 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007321 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007322 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007323}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007324
Reid Spencer832254e2007-02-02 02:16:23 +00007325Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7326 return commonShiftTransforms(I);
7327}
7328
7329Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7330 return commonShiftTransforms(I);
7331}
7332
7333Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007334 if (Instruction *R = commonShiftTransforms(I))
7335 return R;
7336
7337 Value *Op0 = I.getOperand(0);
7338
7339 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7340 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7341 if (CSI->isAllOnesValue())
7342 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007343
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007344 // See if we can turn a signed shr into an unsigned shr.
7345 if (MaskedValueIsZero(Op0,
7346 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7347 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7348
7349 // Arithmetic shifting an all-sign-bit value is a no-op.
7350 unsigned NumSignBits = ComputeNumSignBits(Op0);
7351 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7352 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007353
Chris Lattner348f6652007-12-06 01:59:46 +00007354 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007355}
7356
7357Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7358 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007360
7361 // shl X, 0 == X and shr X, 0 == X
7362 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007363 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7364 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007365 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007366
Reid Spencere4d87aa2006-12-23 06:05:41 +00007367 if (isa<UndefValue>(Op0)) {
7368 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007369 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007370 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007371 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007372 }
7373 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007374 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7375 return ReplaceInstUsesWith(I, Op0);
7376 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007377 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007378 }
7379
Dan Gohman9004c8a2009-05-21 02:28:33 +00007380 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007381 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007382 return &I;
7383
Chris Lattner2eefe512004-04-09 19:05:30 +00007384 // Try to fold constant and into select arguments.
7385 if (isa<Constant>(Op0))
7386 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007387 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007388 return R;
7389
Reid Spencerb83eb642006-10-20 07:07:24 +00007390 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007391 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7392 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393 return 0;
7394}
7395
Reid Spencerb83eb642006-10-20 07:07:24 +00007396Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007397 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007398 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007399
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007400 // See if we can simplify any instructions used by the instruction whose sole
7401 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007402 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007403
Dan Gohmana119de82009-06-14 23:30:43 +00007404 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7405 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007406 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007407 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007408 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007409 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007411 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007413 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007414 }
7415
7416 // ((X*C1) << C2) == (X * (C1 << C2))
7417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7418 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7419 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007420 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007421 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007422
7423 // Try to fold constant and into select arguments.
7424 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7425 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7426 return R;
7427 if (isa<PHINode>(Op0))
7428 if (Instruction *NV = FoldOpIntoPhi(I))
7429 return NV;
7430
Chris Lattner8999dd32007-12-22 09:07:47 +00007431 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7432 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7433 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7434 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7435 // place. Don't try to do this transformation in this case. Also, we
7436 // require that the input operand is a shift-by-constant so that we have
7437 // confidence that the shifts will get folded together. We could do this
7438 // xform in more cases, but it is unlikely to be profitable.
7439 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7440 isa<ConstantInt>(TrOp->getOperand(1))) {
7441 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007442 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007443 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007444 I.getName());
7445 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7446
7447 // For logical shifts, the truncation has the effect of making the high
7448 // part of the register be zeros. Emulate this by inserting an AND to
7449 // clear the top bits as needed. This 'and' will usually be zapped by
7450 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007451 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7452 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007453 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7454
7455 // The mask we constructed says what the trunc would do if occurring
7456 // between the shifts. We want to know the effect *after* the second
7457 // shift. We know that it is a logical shift by a constant, so adjust the
7458 // mask as appropriate.
7459 if (I.getOpcode() == Instruction::Shl)
7460 MaskV <<= Op1->getZExtValue();
7461 else {
7462 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7463 MaskV = MaskV.lshr(Op1->getZExtValue());
7464 }
7465
Owen Andersond672ecb2009-07-03 00:17:18 +00007466 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007467 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007468 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007469 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7470
7471 // Return the value truncated to the interesting size.
7472 return new TruncInst(And, I.getType());
7473 }
7474 }
7475
Chris Lattner4d5542c2006-01-06 07:12:35 +00007476 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007477 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7478 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7479 Value *V1, *V2;
7480 ConstantInt *CC;
7481 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007482 default: break;
7483 case Instruction::Add:
7484 case Instruction::And:
7485 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007486 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007487 // These operators commute.
7488 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007490 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7491 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007492 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007493 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007494 Op0BO->getName());
7495 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007496 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007497 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007498 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007500 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007501 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007502 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007503 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007506 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007507 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007508 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007509 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007510 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007511 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007512 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007513 Op0BO->getOperand(0), Op1,
7514 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007515 InsertNewInstBefore(YS, I); // (Y << C)
7516 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007517 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007518 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007519 V1->getName()+".mask");
7520 InsertNewInstBefore(XM, I); // X & (CC << C)
7521
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007522 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007523 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007524 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007525
Reid Spencera07cb7d2007-02-02 14:41:37 +00007526 // FALL THROUGH.
7527 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007528 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007530 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7531 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007532 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007533 Op0BO->getOperand(1), Op1,
7534 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007536 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007537 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007538 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007539 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007540 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007541 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007542 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007543 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007544
Chris Lattner13d4ab42006-05-31 21:14:00 +00007545 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7547 match(Op0BO->getOperand(0),
7548 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007549 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007550 cast<BinaryOperator>(Op0BO->getOperand(0))
7551 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007552 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007553 Op0BO->getOperand(1), Op1,
7554 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007555 InsertNewInstBefore(YS, I); // (Y << C)
7556 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007557 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007558 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007559 V1->getName()+".mask");
7560 InsertNewInstBefore(XM, I); // X & (CC << C)
7561
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007562 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007563 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007564
Chris Lattner11021cb2005-09-18 05:12:10 +00007565 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007566 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007567 }
7568
7569
7570 // If the operand is an bitwise operator with a constant RHS, and the
7571 // shift is the only use, we can pull it out of the shift.
7572 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7573 bool isValid = true; // Valid only for And, Or, Xor
7574 bool highBitSet = false; // Transform if high bit of constant set?
7575
7576 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007577 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007578 case Instruction::Add:
7579 isValid = isLeftShift;
7580 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007581 case Instruction::Or:
7582 case Instruction::Xor:
7583 highBitSet = false;
7584 break;
7585 case Instruction::And:
7586 highBitSet = true;
7587 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588 }
7589
7590 // If this is a signed shift right, and the high bit is modified
7591 // by the logical operation, do not perform the transformation.
7592 // The highBitSet boolean indicates the value of the high bit of
7593 // the constant which would cause it to be modified for this
7594 // operation.
7595 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007596 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007597 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007598
7599 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007600 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007601
7602 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007603 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007604 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007605 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007606
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007607 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007608 NewRHS);
7609 }
7610 }
7611 }
7612 }
7613
Chris Lattnerad0124c2006-01-06 07:52:12 +00007614 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007615 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7616 if (ShiftOp && !ShiftOp->isShift())
7617 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007618
Reid Spencerb83eb642006-10-20 07:07:24 +00007619 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007620 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007621 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7622 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007623 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7624 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7625 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007626
Zhou Sheng4351c642007-04-02 08:20:41 +00007627 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628
7629 const IntegerType *Ty = cast<IntegerType>(I.getType());
7630
7631 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007632 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007633 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7634 // saturates.
7635 if (AmtSum >= TypeBits) {
7636 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007637 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007638 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7639 }
7640
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007641 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007642 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7644 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007645 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007647
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007649 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007650 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7651 I.getOpcode() == Instruction::LShr) {
7652 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007653 if (AmtSum >= TypeBits)
7654 AmtSum = TypeBits-1;
7655
Chris Lattnerb87056f2007-02-05 00:57:54 +00007656 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007657 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007658 InsertNewInstBefore(Shift, I);
7659
Zhou Shenge9e03f62007-03-28 15:02:20 +00007660 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007661 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007662 }
7663
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664 // Okay, if we get here, one shift must be left, and the other shift must be
7665 // right. See if the amounts are equal.
7666 if (ShiftAmt1 == ShiftAmt2) {
7667 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7668 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007669 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007670 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007671 }
7672 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7673 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007674 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007675 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 }
7677 // We can simplify ((X << C) >>s C) into a trunc + sext.
7678 // NOTE: we could do this for any C, but that would make 'unusual' integer
7679 // types. For now, just stick to ones well-supported by the code
7680 // generators.
7681 const Type *SExtType = 0;
7682 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007683 case 1 :
7684 case 8 :
7685 case 16 :
7686 case 32 :
7687 case 64 :
7688 case 128:
Owen Andersondebcb012009-07-29 22:17:13 +00007689 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007690 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007691 default: break;
7692 }
7693 if (SExtType) {
7694 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7695 InsertNewInstBefore(NewTrunc, I);
7696 return new SExtInst(NewTrunc, Ty);
7697 }
7698 // Otherwise, we can't handle it yet.
7699 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007700 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007701
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007702 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703 if (I.getOpcode() == Instruction::Shl) {
7704 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007706 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007707 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007708 InsertNewInstBefore(Shift, I);
7709
Reid Spencer55702aa2007-03-25 21:11:44 +00007710 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007711 return BinaryOperator::CreateAnd(Shift,
7712 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007713 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007714
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007715 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007716 if (I.getOpcode() == Instruction::LShr) {
7717 assert(ShiftOp->getOpcode() == Instruction::Shl);
7718 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007719 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007721
Reid Spencerd5e30f02007-03-26 17:18:58 +00007722 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007723 return BinaryOperator::CreateAnd(Shift,
7724 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007725 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007726
7727 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7728 } else {
7729 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007730 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007732 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007733 if (I.getOpcode() == Instruction::Shl) {
7734 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7735 ShiftOp->getOpcode() == Instruction::AShr);
7736 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007737 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007738 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007739 InsertNewInstBefore(Shift, I);
7740
Reid Spencer55702aa2007-03-25 21:11:44 +00007741 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007742 return BinaryOperator::CreateAnd(Shift,
7743 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 }
7745
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007746 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007747 if (I.getOpcode() == Instruction::LShr) {
7748 assert(ShiftOp->getOpcode() == Instruction::Shl);
7749 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007750 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007751 InsertNewInstBefore(Shift, I);
7752
Reid Spencer68d27cf2007-03-26 23:45:51 +00007753 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007754 return BinaryOperator::CreateAnd(Shift,
7755 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007756 }
7757
7758 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007759 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007760 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007761 return 0;
7762}
7763
Chris Lattnera1be5662002-05-02 17:06:02 +00007764
Chris Lattnercfd65102005-10-29 04:36:15 +00007765/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7766/// expression. If so, decompose it, returning some value X, such that Val is
7767/// X*Scale+Offset.
7768///
7769static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007770 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007771 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007772 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007773 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007774 Scale = 0;
Owen Andersoneed707b2009-07-24 23:12:02 +00007775 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007776 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7778 if (I->getOpcode() == Instruction::Shl) {
7779 // This is a value scaled by '1 << the shift amt'.
7780 Scale = 1U << RHS->getZExtValue();
7781 Offset = 0;
7782 return I->getOperand(0);
7783 } else if (I->getOpcode() == Instruction::Mul) {
7784 // This value is scaled by 'RHS'.
7785 Scale = RHS->getZExtValue();
7786 Offset = 0;
7787 return I->getOperand(0);
7788 } else if (I->getOpcode() == Instruction::Add) {
7789 // We have X+C. Check to see if we really have (X*C2)+C1,
7790 // where C1 is divisible by C2.
7791 unsigned SubScale;
7792 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007793 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7794 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007795 Offset += RHS->getZExtValue();
7796 Scale = SubScale;
7797 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007798 }
7799 }
7800 }
7801
7802 // Otherwise, we can't look past this.
7803 Scale = 1;
7804 Offset = 0;
7805 return Val;
7806}
7807
7808
Chris Lattnerb3f83972005-10-24 06:03:58 +00007809/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7810/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007811Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007812 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007813 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007814
Chris Lattnerb53c2382005-10-24 06:22:12 +00007815 // Remove any uses of AI that are dead.
7816 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007817
Chris Lattnerb53c2382005-10-24 06:22:12 +00007818 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7819 Instruction *User = cast<Instruction>(*UI++);
7820 if (isInstructionTriviallyDead(User)) {
7821 while (UI != E && *UI == User)
7822 ++UI; // If this instruction uses AI more than once, don't break UI.
7823
Chris Lattnerb53c2382005-10-24 06:22:12 +00007824 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007825 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007826 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007827 }
7828 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007829
7830 // This requires TargetData to get the alloca alignment and size information.
7831 if (!TD) return 0;
7832
Chris Lattnerb3f83972005-10-24 06:03:58 +00007833 // Get the type really allocated and the type casted to.
7834 const Type *AllocElTy = AI.getAllocatedType();
7835 const Type *CastElTy = PTy->getElementType();
7836 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007837
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007838 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7839 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007840 if (CastElTyAlign < AllocElTyAlign) return 0;
7841
Chris Lattner39387a52005-10-24 06:35:18 +00007842 // If the allocation has multiple uses, only promote it if we are strictly
7843 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007844 // same, we open the door to infinite loops of various kinds. (A reference
7845 // from a dbg.declare doesn't count as a use for this purpose.)
7846 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7847 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007848
Duncan Sands777d2302009-05-09 07:06:46 +00007849 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7850 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007851 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007852
Chris Lattner455fcc82005-10-29 03:19:53 +00007853 // See if we can satisfy the modulus by pulling a scale out of the array
7854 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007855 unsigned ArraySizeScale;
7856 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007857 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007858 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7859 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007860
Chris Lattner455fcc82005-10-29 03:19:53 +00007861 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7862 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007863 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7864 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007865
Chris Lattner455fcc82005-10-29 03:19:53 +00007866 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7867 Value *Amt = 0;
7868 if (Scale == 1) {
7869 Amt = NumElements;
7870 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007871 // If the allocation size is constant, form a constant mul expression
Owen Andersoneed707b2009-07-24 23:12:02 +00007872 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007873 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007874 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007875 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007876 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007877 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007878 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007879 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007880 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007881 }
7882
Jeff Cohen86796be2007-04-04 16:58:57 +00007883 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007884 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007885 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007886 Amt = InsertNewInstBefore(Tmp, AI);
7887 }
7888
Chris Lattnerb3f83972005-10-24 06:03:58 +00007889 AllocationInst *New;
7890 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007891 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007892 else
Owen Anderson50dead02009-07-15 23:53:25 +00007893 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007894 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007895 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007896
Dale Johannesena0a66372009-03-05 00:39:02 +00007897 // If the allocation has one real use plus a dbg.declare, just remove the
7898 // declare.
7899 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7900 EraseInstFromFunction(*DI);
7901 }
7902 // If the allocation has multiple real uses, insert a cast and change all
7903 // things that used it to use the new cast. This will also hack on CI, but it
7904 // will die soon.
7905 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007906 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007907 // New is the allocation instruction, pointer typed. AI is the original
7908 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7909 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007910 InsertNewInstBefore(NewCast, AI);
7911 AI.replaceAllUsesWith(NewCast);
7912 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007913 return ReplaceInstUsesWith(CI, New);
7914}
7915
Chris Lattner70074e02006-05-13 02:06:03 +00007916/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007917/// and return it as type Ty without inserting any new casts and without
7918/// changing the computed value. This is used by code that tries to decide
7919/// whether promoting or shrinking integer operations to wider or smaller types
7920/// will allow us to eliminate a truncate or extend.
7921///
7922/// This is a truncation operation if Ty is smaller than V->getType(), or an
7923/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007924///
7925/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7926/// should return true if trunc(V) can be computed by computing V in the smaller
7927/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7928/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7929/// efficiently truncated.
7930///
7931/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7932/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7933/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007934bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007935 unsigned CastOpc,
7936 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007937 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007938 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007939 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007940
7941 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007942 if (!I) return false;
7943
Dan Gohman6de29f82009-06-15 22:12:54 +00007944 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007945
Chris Lattner951626b2007-08-02 06:11:14 +00007946 // If this is an extension or truncate, we can often eliminate it.
7947 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7948 // If this is a cast from the destination type, we can trivially eliminate
7949 // it, and this will remove a cast overall.
7950 if (I->getOperand(0)->getType() == Ty) {
7951 // If the first operand is itself a cast, and is eliminable, do not count
7952 // this as an eliminable cast. We would prefer to eliminate those two
7953 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007954 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007955 ++NumCastsRemoved;
7956 return true;
7957 }
7958 }
7959
7960 // We can't extend or shrink something that has multiple uses: doing so would
7961 // require duplicating the instruction in general, which isn't profitable.
7962 if (!I->hasOneUse()) return false;
7963
Evan Chengf35fd542009-01-15 17:01:23 +00007964 unsigned Opc = I->getOpcode();
7965 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007966 case Instruction::Add:
7967 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007968 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007969 case Instruction::And:
7970 case Instruction::Or:
7971 case Instruction::Xor:
7972 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007973 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007974 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007975 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007976 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007977
Eli Friedman070a9812009-07-13 22:46:01 +00007978 case Instruction::UDiv:
7979 case Instruction::URem: {
7980 // UDiv and URem can be truncated if all the truncated bits are zero.
7981 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7982 uint32_t BitWidth = Ty->getScalarSizeInBits();
7983 if (BitWidth < OrigBitWidth) {
7984 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7985 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7986 MaskedValueIsZero(I->getOperand(1), Mask)) {
7987 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7988 NumCastsRemoved) &&
7989 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7990 NumCastsRemoved);
7991 }
7992 }
7993 break;
7994 }
Chris Lattner46b96052006-11-29 07:18:39 +00007995 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007996 // If we are truncating the result of this SHL, and if it's a shift of a
7997 // constant amount, we can always perform a SHL in a smaller type.
7998 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007999 uint32_t BitWidth = Ty->getScalarSizeInBits();
8000 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008001 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008002 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008003 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008004 }
8005 break;
8006 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008007 // If this is a truncate of a logical shr, we can truncate it to a smaller
8008 // lshr iff we know that the bits we would otherwise be shifting in are
8009 // already zeros.
8010 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008011 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8012 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008013 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008014 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008015 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8016 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008017 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008018 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008019 }
8020 }
Chris Lattner46b96052006-11-29 07:18:39 +00008021 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008022 case Instruction::ZExt:
8023 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008024 case Instruction::Trunc:
8025 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008026 // can safely replace it. Note that replacing it does not reduce the number
8027 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008028 if (Opc == CastOpc)
8029 return true;
8030
8031 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008032 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008033 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008034 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008035 case Instruction::Select: {
8036 SelectInst *SI = cast<SelectInst>(I);
8037 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008038 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008039 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008040 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008041 }
Chris Lattner8114b712008-06-18 04:00:49 +00008042 case Instruction::PHI: {
8043 // We can change a phi if we can change all operands.
8044 PHINode *PN = cast<PHINode>(I);
8045 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8046 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008047 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008048 return false;
8049 return true;
8050 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008051 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008052 // TODO: Can handle more cases here.
8053 break;
8054 }
8055
8056 return false;
8057}
8058
8059/// EvaluateInDifferentType - Given an expression that
8060/// CanEvaluateInDifferentType returns true for, actually insert the code to
8061/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008062Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008063 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008064 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008065 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008066 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008067
8068 // Otherwise, it must be an instruction.
8069 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008070 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008071 unsigned Opc = I->getOpcode();
8072 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008073 case Instruction::Add:
8074 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008075 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008076 case Instruction::And:
8077 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008078 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008079 case Instruction::AShr:
8080 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008081 case Instruction::Shl:
8082 case Instruction::UDiv:
8083 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008084 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008085 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008086 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008087 break;
8088 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008089 case Instruction::Trunc:
8090 case Instruction::ZExt:
8091 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008092 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008093 // just return the source. There's no need to insert it because it is not
8094 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008095 if (I->getOperand(0)->getType() == Ty)
8096 return I->getOperand(0);
8097
Chris Lattner8114b712008-06-18 04:00:49 +00008098 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008099 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008100 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008101 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008102 case Instruction::Select: {
8103 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8104 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8105 Res = SelectInst::Create(I->getOperand(0), True, False);
8106 break;
8107 }
Chris Lattner8114b712008-06-18 04:00:49 +00008108 case Instruction::PHI: {
8109 PHINode *OPN = cast<PHINode>(I);
8110 PHINode *NPN = PHINode::Create(Ty);
8111 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8112 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8113 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8114 }
8115 Res = NPN;
8116 break;
8117 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008118 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008119 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008120 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008121 break;
8122 }
8123
Chris Lattner8114b712008-06-18 04:00:49 +00008124 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008125 return InsertNewInstBefore(Res, *I);
8126}
8127
Reid Spencer3da59db2006-11-27 01:05:10 +00008128/// @brief Implement the transforms common to all CastInst visitors.
8129Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008130 Value *Src = CI.getOperand(0);
8131
Dan Gohman23d9d272007-05-11 21:10:54 +00008132 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008133 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008134 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008135 if (Instruction::CastOps opc =
8136 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8137 // The first cast (CSrc) is eliminable so we need to fix up or replace
8138 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008139 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008140 }
8141 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008142
Reid Spencer3da59db2006-11-27 01:05:10 +00008143 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008144 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8145 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8146 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008147
8148 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008149 if (isa<PHINode>(Src))
8150 if (Instruction *NV = FoldOpIntoPhi(CI))
8151 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008152
Reid Spencer3da59db2006-11-27 01:05:10 +00008153 return 0;
8154}
8155
Chris Lattner46cd5a12009-01-09 05:44:56 +00008156/// FindElementAtOffset - Given a type and a constant offset, determine whether
8157/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008158/// the specified offset. If so, fill them into NewIndices and return the
8159/// resultant element type, otherwise return null.
8160static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8161 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008162 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008163 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008164 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008165 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008166
8167 // Start with the index over the outer type. Note that the type size
8168 // might be zero (even if the offset isn't zero) if the indexed type
8169 // is something like [0 x {int, int}]
8170 const Type *IntPtrTy = TD->getIntPtrType();
8171 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008172 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008173 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008174 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008175
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008176 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177 if (Offset < 0) {
8178 --FirstIdx;
8179 Offset += TySize;
8180 assert(Offset >= 0);
8181 }
8182 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8183 }
8184
Owen Andersoneed707b2009-07-24 23:12:02 +00008185 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008186
8187 // Index into the types. If we fail, set OrigBase to null.
8188 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008189 // Indexing into tail padding between struct/array elements.
8190 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008191 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008192
Chris Lattner46cd5a12009-01-09 05:44:56 +00008193 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8194 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008195 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8196 "Offset must stay within the indexed type");
8197
Chris Lattner46cd5a12009-01-09 05:44:56 +00008198 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneed707b2009-07-24 23:12:02 +00008199 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008200
8201 Offset -= SL->getElementOffset(Elt);
8202 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008203 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008204 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008205 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008206 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008207 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008208 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008209 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008210 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008211 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008212 }
8213 }
8214
Chris Lattner3914f722009-01-24 01:00:13 +00008215 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008216}
8217
Chris Lattnerd3e28342007-04-27 17:44:50 +00008218/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8219Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8220 Value *Src = CI.getOperand(0);
8221
Chris Lattnerd3e28342007-04-27 17:44:50 +00008222 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008223 // If casting the result of a getelementptr instruction with no offset, turn
8224 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008225 if (GEP->hasAllZeroIndices()) {
8226 // Changing the cast operand is usually not a good idea but it is safe
8227 // here because the pointer operand is being replaced with another
8228 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008229 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008230 CI.setOperand(0, GEP->getOperand(0));
8231 return &CI;
8232 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008233
8234 // If the GEP has a single use, and the base pointer is a bitcast, and the
8235 // GEP computes a constant offset, see if we can convert these three
8236 // instructions into fewer. This typically happens with unions and other
8237 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008238 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008239 if (GEP->hasAllConstantIndices()) {
8240 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008241 ConstantInt *OffsetV =
8242 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008243 int64_t Offset = OffsetV->getSExtValue();
8244
8245 // Get the base pointer input of the bitcast, and the type it points to.
8246 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8247 const Type *GEPIdxTy =
8248 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008249 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008250 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008251 // If we were able to index down into an element, create the GEP
8252 // and bitcast the result. This eliminates one bitcast, potentially
8253 // two.
8254 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8255 NewIndices.begin(),
8256 NewIndices.end(), "");
8257 InsertNewInstBefore(NGEP, CI);
8258 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008259 if (cast<GEPOperator>(GEP)->isInBounds())
8260 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008261
Chris Lattner46cd5a12009-01-09 05:44:56 +00008262 if (isa<BitCastInst>(CI))
8263 return new BitCastInst(NGEP, CI.getType());
8264 assert(isa<PtrToIntInst>(CI));
8265 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008266 }
8267 }
8268 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008269 }
8270
8271 return commonCastTransforms(CI);
8272}
8273
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008274/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8275/// type like i42. We don't want to introduce operations on random non-legal
8276/// integer types where they don't already exist in the code. In the future,
8277/// we should consider making this based off target-data, so that 32-bit targets
8278/// won't get i64 operations etc.
8279static bool isSafeIntegerType(const Type *Ty) {
8280 switch (Ty->getPrimitiveSizeInBits()) {
8281 case 8:
8282 case 16:
8283 case 32:
8284 case 64:
8285 return true;
8286 default:
8287 return false;
8288 }
8289}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008290
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008291/// commonIntCastTransforms - This function implements the common transforms
8292/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008293Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8294 if (Instruction *Result = commonCastTransforms(CI))
8295 return Result;
8296
8297 Value *Src = CI.getOperand(0);
8298 const Type *SrcTy = Src->getType();
8299 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008300 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8301 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008302
Reid Spencer3da59db2006-11-27 01:05:10 +00008303 // See if we can simplify any instructions used by the LHS whose sole
8304 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008305 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008306 return &CI;
8307
8308 // If the source isn't an instruction or has more than one use then we
8309 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008310 Instruction *SrcI = dyn_cast<Instruction>(Src);
8311 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 return 0;
8313
Chris Lattnerc739cd62007-03-03 05:27:34 +00008314 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008315 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008316 // Only do this if the dest type is a simple type, don't convert the
8317 // expression tree to something weird like i93 unless the source is also
8318 // strange.
8319 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008320 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8321 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008322 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008323 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008324 // eliminates the cast, so it is always a win. If this is a zero-extension,
8325 // we need to do an AND to maintain the clear top-part of the computation,
8326 // so we require that the input have eliminated at least one cast. If this
8327 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008328 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008329 bool DoXForm = false;
8330 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008331 switch (CI.getOpcode()) {
8332 default:
8333 // All the others use floating point so we shouldn't actually
8334 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008335 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008336 case Instruction::Trunc:
8337 DoXForm = true;
8338 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008339 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008340 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008341 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008342 // If it's unnecessary to issue an AND to clear the high bits, it's
8343 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008344 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008345 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8346 if (MaskedValueIsZero(TryRes, Mask))
8347 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008348
8349 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008350 if (TryI->use_empty())
8351 EraseInstFromFunction(*TryI);
8352 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008353 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008354 }
Evan Chengf35fd542009-01-15 17:01:23 +00008355 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008356 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008357 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008358 // If we do not have to emit the truncate + sext pair, then it's always
8359 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008360 //
8361 // It's not safe to eliminate the trunc + sext pair if one of the
8362 // eliminated cast is a truncate. e.g.
8363 // t2 = trunc i32 t1 to i16
8364 // t3 = sext i16 t2 to i32
8365 // !=
8366 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008367 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008368 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8369 if (NumSignBits > (DestBitSize - SrcBitSize))
8370 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008371
8372 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008373 if (TryI->use_empty())
8374 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008375 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008376 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008377 }
Evan Chengf35fd542009-01-15 17:01:23 +00008378 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008379
8380 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008381 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8382 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008383 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8384 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008385 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008386 // Just replace this cast with the result.
8387 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008388
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 assert(Res->getType() == DestTy);
8390 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008391 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008392 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 // Just replace this cast with the result.
8394 return ReplaceInstUsesWith(CI, Res);
8395 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008396 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008397
8398 // If the high bits are already zero, just replace this cast with the
8399 // result.
8400 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8401 if (MaskedValueIsZero(Res, Mask))
8402 return ReplaceInstUsesWith(CI, Res);
8403
8404 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008405 Constant *C = ConstantInt::get(*Context,
8406 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008407 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008408 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008409 case Instruction::SExt: {
8410 // If the high bits are already filled with sign bit, just replace this
8411 // cast with the result.
8412 unsigned NumSignBits = ComputeNumSignBits(Res);
8413 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008414 return ReplaceInstUsesWith(CI, Res);
8415
Reid Spencer3da59db2006-11-27 01:05:10 +00008416 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008417 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008418 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8419 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008421 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008422 }
8423 }
8424
8425 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8426 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8427
8428 switch (SrcI->getOpcode()) {
8429 case Instruction::Add:
8430 case Instruction::Mul:
8431 case Instruction::And:
8432 case Instruction::Or:
8433 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008434 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008435 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8436 // Don't insert two casts unless at least one can be eliminated.
8437 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008438 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008439 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8440 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008441 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008442 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008443 }
8444 }
8445
8446 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8447 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8448 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008449 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008450 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008451 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008452 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008453 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008454 }
8455 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008456
Eli Friedman65445c52009-07-13 21:45:57 +00008457 case Instruction::Shl: {
8458 // Canonicalize trunc inside shl, if we can.
8459 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8460 if (CI && DestBitSize < SrcBitSize &&
8461 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8462 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8463 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008464 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008465 }
8466 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008467 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008468 }
8469 return 0;
8470}
8471
Chris Lattner8a9f5712007-04-11 06:57:46 +00008472Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008473 if (Instruction *Result = commonIntCastTransforms(CI))
8474 return Result;
8475
8476 Value *Src = CI.getOperand(0);
8477 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008478 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8479 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008480
8481 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008482 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008483 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008484 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008485 Value *Zero = Constant::getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008486 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008487 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008488
Chris Lattner4f9797d2009-03-24 18:15:30 +00008489 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8490 ConstantInt *ShAmtV = 0;
8491 Value *ShiftOp = 0;
8492 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008493 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008494 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8495
8496 // Get a mask for the bits shifting in.
8497 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8498 if (MaskedValueIsZero(ShiftOp, Mask)) {
8499 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008500 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008501
8502 // Okay, we can shrink this. Truncate the input, then return a new
8503 // shift.
8504 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008505 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008506 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008507 }
8508 }
8509
8510 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008511}
8512
Evan Chengb98a10e2008-03-24 00:21:34 +00008513/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8514/// in order to eliminate the icmp.
8515Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8516 bool DoXform) {
8517 // If we are just checking for a icmp eq of a single bit and zext'ing it
8518 // to an integer, then shift the bit to the appropriate place and then
8519 // cast to integer to avoid the comparison.
8520 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8521 const APInt &Op1CV = Op1C->getValue();
8522
8523 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8524 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8525 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8526 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8527 if (!DoXform) return ICI;
8528
8529 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008530 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008531 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008532 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008533 In->getName()+".lobit"),
8534 CI);
8535 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008536 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008537 false/*ZExt*/, "tmp", &CI);
8538
8539 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008540 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008541 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008542 In->getName()+".not"),
8543 CI);
8544 }
8545
8546 return ReplaceInstUsesWith(CI, In);
8547 }
8548
8549
8550
8551 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8552 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8553 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8554 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8555 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8556 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8557 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8558 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8559 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8560 // This only works for EQ and NE
8561 ICI->isEquality()) {
8562 // If Op1C some other power of two, convert:
8563 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8564 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8565 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8566 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8567
8568 APInt KnownZeroMask(~KnownZero);
8569 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8570 if (!DoXform) return ICI;
8571
8572 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8573 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8574 // (X&4) == 2 --> false
8575 // (X&4) != 2 --> true
Owen Andersoneed707b2009-07-24 23:12:02 +00008576 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008577 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008578 return ReplaceInstUsesWith(CI, Res);
8579 }
8580
8581 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8582 Value *In = ICI->getOperand(0);
8583 if (ShiftAmt) {
8584 // Perform a logical shr by shiftamt.
8585 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008586 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008587 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008588 In->getName()+".lobit"), CI);
8589 }
8590
8591 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008592 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008593 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008594 InsertNewInstBefore(cast<Instruction>(In), CI);
8595 }
8596
8597 if (CI.getType() == In->getType())
8598 return ReplaceInstUsesWith(CI, In);
8599 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008600 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008601 }
8602 }
8603 }
8604
8605 return 0;
8606}
8607
Chris Lattner8a9f5712007-04-11 06:57:46 +00008608Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008609 // If one of the common conversion will work ..
8610 if (Instruction *Result = commonIntCastTransforms(CI))
8611 return Result;
8612
8613 Value *Src = CI.getOperand(0);
8614
Chris Lattnera84f47c2009-02-17 20:47:23 +00008615 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8616 // types and if the sizes are just right we can convert this into a logical
8617 // 'and' which will be much cheaper than the pair of casts.
8618 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8619 // Get the sizes of the types involved. We know that the intermediate type
8620 // will be smaller than A or C, but don't know the relation between A and C.
8621 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008622 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8623 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8624 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008625 // If we're actually extending zero bits, then if
8626 // SrcSize < DstSize: zext(a & mask)
8627 // SrcSize == DstSize: a & mask
8628 // SrcSize > DstSize: trunc(a) & mask
8629 if (SrcSize < DstSize) {
8630 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008631 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008632 Instruction *And =
8633 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8634 InsertNewInstBefore(And, CI);
8635 return new ZExtInst(And, CI.getType());
8636 } else if (SrcSize == DstSize) {
8637 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008638 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008639 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008640 } else if (SrcSize > DstSize) {
8641 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8642 InsertNewInstBefore(Trunc, CI);
8643 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008644 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008645 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008646 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008647 }
8648 }
8649
Evan Chengb98a10e2008-03-24 00:21:34 +00008650 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8651 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008652
Evan Chengb98a10e2008-03-24 00:21:34 +00008653 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8654 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8655 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8656 // of the (zext icmp) will be transformed.
8657 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8658 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8659 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8660 (transformZExtICmp(LHS, CI, false) ||
8661 transformZExtICmp(RHS, CI, false))) {
8662 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8663 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008664 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008665 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008666 }
8667
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008668 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008669 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8670 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8671 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8672 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008673 if (TI0->getType() == CI.getType())
8674 return
8675 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008676 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008677 }
8678
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008679 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8680 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8681 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8682 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8683 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8684 And->getOperand(1) == C)
8685 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8686 Value *TI0 = TI->getOperand(0);
8687 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008688 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008689 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8690 InsertNewInstBefore(NewAnd, *And);
8691 return BinaryOperator::CreateXor(NewAnd, ZC);
8692 }
8693 }
8694
Reid Spencer3da59db2006-11-27 01:05:10 +00008695 return 0;
8696}
8697
Chris Lattner8a9f5712007-04-11 06:57:46 +00008698Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008699 if (Instruction *I = commonIntCastTransforms(CI))
8700 return I;
8701
Chris Lattner8a9f5712007-04-11 06:57:46 +00008702 Value *Src = CI.getOperand(0);
8703
Dan Gohman1975d032008-10-30 20:40:10 +00008704 // Canonicalize sign-extend from i1 to a select.
8705 if (Src->getType() == Type::Int1Ty)
8706 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008707 Constant::getAllOnesValue(CI.getType()),
8708 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008709
8710 // See if the value being truncated is already sign extended. If so, just
8711 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008712 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008713 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008714 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8715 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8716 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008717 unsigned NumSignBits = ComputeNumSignBits(Op);
8718
8719 if (OpBits == DestBits) {
8720 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8721 // bits, it is already ready.
8722 if (NumSignBits > DestBits-MidBits)
8723 return ReplaceInstUsesWith(CI, Op);
8724 } else if (OpBits < DestBits) {
8725 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8726 // bits, just sext from i32.
8727 if (NumSignBits > OpBits-MidBits)
8728 return new SExtInst(Op, CI.getType(), "tmp");
8729 } else {
8730 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8731 // bits, just truncate to i32.
8732 if (NumSignBits > OpBits-MidBits)
8733 return new TruncInst(Op, CI.getType(), "tmp");
8734 }
8735 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008736
8737 // If the input is a shl/ashr pair of a same constant, then this is a sign
8738 // extension from a smaller value. If we could trust arbitrary bitwidth
8739 // integers, we could turn this into a truncate to the smaller bit and then
8740 // use a sext for the whole extension. Since we don't, look deeper and check
8741 // for a truncate. If the source and dest are the same type, eliminate the
8742 // trunc and extend and just do shifts. For example, turn:
8743 // %a = trunc i32 %i to i8
8744 // %b = shl i8 %a, 6
8745 // %c = ashr i8 %b, 6
8746 // %d = sext i8 %c to i32
8747 // into:
8748 // %a = shl i32 %i, 30
8749 // %d = ashr i32 %a, 30
8750 Value *A = 0;
8751 ConstantInt *BA = 0, *CA = 0;
8752 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008753 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008754 BA == CA && isa<TruncInst>(A)) {
8755 Value *I = cast<TruncInst>(A)->getOperand(0);
8756 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008757 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8758 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008759 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008760 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008761 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8762 CI.getName()), CI);
8763 return BinaryOperator::CreateAShr(I, ShAmtV);
8764 }
8765 }
8766
Chris Lattnerba417832007-04-11 06:12:58 +00008767 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008768}
8769
Chris Lattnerb7530652008-01-27 05:29:54 +00008770/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8771/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008772static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008773 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008774 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008775 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008776 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8777 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008778 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008779 return 0;
8780}
8781
8782/// LookThroughFPExtensions - If this is an fp extension instruction, look
8783/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008784static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008785 if (Instruction *I = dyn_cast<Instruction>(V))
8786 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008787 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008788
8789 // If this value is a constant, return the constant in the smallest FP type
8790 // that can accurately represent it. This allows us to turn
8791 // (float)((double)X+2.0) into x+2.0f.
8792 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8793 if (CFP->getType() == Type::PPC_FP128Ty)
8794 return V; // No constant folding of this.
8795 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008796 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008797 return V;
8798 if (CFP->getType() == Type::DoubleTy)
8799 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008800 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008801 return V;
8802 // Don't try to shrink to various long double types.
8803 }
8804
8805 return V;
8806}
8807
8808Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8809 if (Instruction *I = commonCastTransforms(CI))
8810 return I;
8811
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008812 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008813 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008814 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008815 // many builtins (sqrt, etc).
8816 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8817 if (OpI && OpI->hasOneUse()) {
8818 switch (OpI->getOpcode()) {
8819 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008820 case Instruction::FAdd:
8821 case Instruction::FSub:
8822 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008823 case Instruction::FDiv:
8824 case Instruction::FRem:
8825 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008826 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8827 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008828 if (LHSTrunc->getType() != SrcTy &&
8829 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008830 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008831 // If the source types were both smaller than the destination type of
8832 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008833 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8834 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008835 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8836 CI.getType(), CI);
8837 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8838 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008839 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008840 }
8841 }
8842 break;
8843 }
8844 }
8845 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008846}
8847
8848Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8849 return commonCastTransforms(CI);
8850}
8851
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008852Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008853 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8854 if (OpI == 0)
8855 return commonCastTransforms(FI);
8856
8857 // fptoui(uitofp(X)) --> X
8858 // fptoui(sitofp(X)) --> X
8859 // This is safe if the intermediate type has enough bits in its mantissa to
8860 // accurately represent all values of X. For example, do not do this with
8861 // i64->float->i64. This is also safe for sitofp case, because any negative
8862 // 'X' value would cause an undefined result for the fptoui.
8863 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8864 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008865 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008866 OpI->getType()->getFPMantissaWidth())
8867 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008868
8869 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008870}
8871
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008872Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008873 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8874 if (OpI == 0)
8875 return commonCastTransforms(FI);
8876
8877 // fptosi(sitofp(X)) --> X
8878 // fptosi(uitofp(X)) --> X
8879 // This is safe if the intermediate type has enough bits in its mantissa to
8880 // accurately represent all values of X. For example, do not do this with
8881 // i64->float->i64. This is also safe for sitofp case, because any negative
8882 // 'X' value would cause an undefined result for the fptoui.
8883 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8884 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008885 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008886 OpI->getType()->getFPMantissaWidth())
8887 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008888
8889 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008890}
8891
8892Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8893 return commonCastTransforms(CI);
8894}
8895
8896Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8897 return commonCastTransforms(CI);
8898}
8899
Chris Lattnera0e69692009-03-24 18:35:40 +00008900Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8901 // If the destination integer type is smaller than the intptr_t type for
8902 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8903 // trunc to be exposed to other transforms. Don't do this for extending
8904 // ptrtoint's, because we don't know if the target sign or zero extends its
8905 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008906 if (TD &&
8907 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008908 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8909 TD->getIntPtrType(),
8910 "tmp"), CI);
8911 return new TruncInst(P, CI.getType());
8912 }
8913
Chris Lattnerd3e28342007-04-27 17:44:50 +00008914 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008915}
8916
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008917Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008918 // If the source integer type is larger than the intptr_t type for
8919 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8920 // allows the trunc to be exposed to other transforms. Don't do this for
8921 // extending inttoptr's, because we don't know if the target sign or zero
8922 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008923 if (TD &&
8924 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008925 TD->getPointerSizeInBits()) {
8926 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8927 TD->getIntPtrType(),
8928 "tmp"), CI);
8929 return new IntToPtrInst(P, CI.getType());
8930 }
8931
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008932 if (Instruction *I = commonCastTransforms(CI))
8933 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008934
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008935 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008936}
8937
Chris Lattnerd3e28342007-04-27 17:44:50 +00008938Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008939 // If the operands are integer typed then apply the integer transforms,
8940 // otherwise just apply the common ones.
8941 Value *Src = CI.getOperand(0);
8942 const Type *SrcTy = Src->getType();
8943 const Type *DestTy = CI.getType();
8944
Eli Friedman7e25d452009-07-13 20:53:00 +00008945 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008946 if (Instruction *I = commonPointerCastTransforms(CI))
8947 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008948 } else {
8949 if (Instruction *Result = commonCastTransforms(CI))
8950 return Result;
8951 }
8952
8953
8954 // Get rid of casts from one type to the same type. These are useless and can
8955 // be replaced by the operand.
8956 if (DestTy == Src->getType())
8957 return ReplaceInstUsesWith(CI, Src);
8958
Reid Spencer3da59db2006-11-27 01:05:10 +00008959 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008960 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8961 const Type *DstElTy = DstPTy->getElementType();
8962 const Type *SrcElTy = SrcPTy->getElementType();
8963
Nate Begeman83ad90a2008-03-31 00:22:16 +00008964 // If the address spaces don't match, don't eliminate the bitcast, which is
8965 // required for changing types.
8966 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8967 return 0;
8968
Chris Lattnerd3e28342007-04-27 17:44:50 +00008969 // If we are casting a malloc or alloca to a pointer to a type of the same
8970 // size, rewrite the allocation instruction to allocate the "right" type.
8971 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8972 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8973 return V;
8974
Chris Lattnerd717c182007-05-05 22:32:24 +00008975 // If the source and destination are pointers, and this cast is equivalent
8976 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008977 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersona7235ea2009-07-31 20:28:14 +00008978 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008979 unsigned NumZeros = 0;
8980 while (SrcElTy != DstElTy &&
8981 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8982 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8983 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8984 ++NumZeros;
8985 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008986
Chris Lattnerd3e28342007-04-27 17:44:50 +00008987 // If we found a path from the src to dest, create the getelementptr now.
8988 if (SrcElTy == DstElTy) {
8989 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008990 Instruction *GEP = GetElementPtrInst::Create(Src,
8991 Idxs.begin(), Idxs.end(), "",
8992 ((Instruction*) NULL));
8993 cast<GEPOperator>(GEP)->setIsInBounds(true);
8994 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008995 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008996 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008997
Eli Friedman2451a642009-07-18 23:06:53 +00008998 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8999 if (DestVTy->getNumElements() == 1) {
9000 if (!isa<VectorType>(SrcTy)) {
9001 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9002 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009003 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Andersona7235ea2009-07-31 20:28:14 +00009004 Constant::getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00009005 }
9006 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9007 }
9008 }
9009
9010 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9011 if (SrcVTy->getNumElements() == 1) {
9012 if (!isa<VectorType>(DestTy)) {
9013 Instruction *Elem =
Owen Andersona7235ea2009-07-31 20:28:14 +00009014 ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00009015 InsertNewInstBefore(Elem, CI);
9016 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9017 }
9018 }
9019 }
9020
Reid Spencer3da59db2006-11-27 01:05:10 +00009021 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9022 if (SVI->hasOneUse()) {
9023 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9024 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009025 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009026 cast<VectorType>(DestTy)->getNumElements() ==
9027 SVI->getType()->getNumElements() &&
9028 SVI->getType()->getNumElements() ==
9029 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009030 CastInst *Tmp;
9031 // If either of the operands is a cast from CI.getType(), then
9032 // evaluating the shuffle in the casted destination's type will allow
9033 // us to eliminate at least one cast.
9034 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9035 Tmp->getOperand(0)->getType() == DestTy) ||
9036 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9037 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009038 Value *LHS = InsertCastBefore(Instruction::BitCast,
9039 SVI->getOperand(0), DestTy, CI);
9040 Value *RHS = InsertCastBefore(Instruction::BitCast,
9041 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009042 // Return a new shuffle vector. Use the same element ID's, as we
9043 // know the vector types match #elts.
9044 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009045 }
9046 }
9047 }
9048 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009049 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009050}
9051
Chris Lattnere576b912004-04-09 23:46:01 +00009052/// GetSelectFoldableOperands - We want to turn code that looks like this:
9053/// %C = or %A, %B
9054/// %D = select %cond, %C, %A
9055/// into:
9056/// %C = select %cond, %B, 0
9057/// %D = or %A, %C
9058///
9059/// Assuming that the specified instruction is an operand to the select, return
9060/// a bitmask indicating which operands of this instruction are foldable if they
9061/// equal the other incoming value of the select.
9062///
9063static unsigned GetSelectFoldableOperands(Instruction *I) {
9064 switch (I->getOpcode()) {
9065 case Instruction::Add:
9066 case Instruction::Mul:
9067 case Instruction::And:
9068 case Instruction::Or:
9069 case Instruction::Xor:
9070 return 3; // Can fold through either operand.
9071 case Instruction::Sub: // Can only fold on the amount subtracted.
9072 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009073 case Instruction::LShr:
9074 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009075 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009076 default:
9077 return 0; // Cannot fold
9078 }
9079}
9080
9081/// GetSelectFoldableConstant - For the same transformation as the previous
9082/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009083static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009084 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009085 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009086 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009087 case Instruction::Add:
9088 case Instruction::Sub:
9089 case Instruction::Or:
9090 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009091 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009092 case Instruction::LShr:
9093 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009094 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009095 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009096 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009097 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009098 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009099 }
9100}
9101
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009102/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9103/// have the same opcode and only one use each. Try to simplify this.
9104Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9105 Instruction *FI) {
9106 if (TI->getNumOperands() == 1) {
9107 // If this is a non-volatile load or a cast from the same type,
9108 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009109 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009110 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9111 return 0;
9112 } else {
9113 return 0; // unknown unary op.
9114 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009115
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009116 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009117 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009118 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009120 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009121 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009122 }
9123
Reid Spencer832254e2007-02-02 02:16:23 +00009124 // Only handle binary operators here.
9125 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009126 return 0;
9127
9128 // Figure out if the operations have any operands in common.
9129 Value *MatchOp, *OtherOpT, *OtherOpF;
9130 bool MatchIsOpZero;
9131 if (TI->getOperand(0) == FI->getOperand(0)) {
9132 MatchOp = TI->getOperand(0);
9133 OtherOpT = TI->getOperand(1);
9134 OtherOpF = FI->getOperand(1);
9135 MatchIsOpZero = true;
9136 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9137 MatchOp = TI->getOperand(1);
9138 OtherOpT = TI->getOperand(0);
9139 OtherOpF = FI->getOperand(0);
9140 MatchIsOpZero = false;
9141 } else if (!TI->isCommutative()) {
9142 return 0;
9143 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9144 MatchOp = TI->getOperand(0);
9145 OtherOpT = TI->getOperand(1);
9146 OtherOpF = FI->getOperand(0);
9147 MatchIsOpZero = true;
9148 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9149 MatchOp = TI->getOperand(1);
9150 OtherOpT = TI->getOperand(0);
9151 OtherOpF = FI->getOperand(1);
9152 MatchIsOpZero = true;
9153 } else {
9154 return 0;
9155 }
9156
9157 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009158 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9159 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009160 InsertNewInstBefore(NewSI, SI);
9161
9162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9163 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009164 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009165 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009166 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009167 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009168 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009169 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009170}
9171
Evan Chengde621922009-03-31 20:42:45 +00009172static bool isSelect01(Constant *C1, Constant *C2) {
9173 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9174 if (!C1I)
9175 return false;
9176 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9177 if (!C2I)
9178 return false;
9179 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9180}
9181
9182/// FoldSelectIntoOp - Try fold the select into one of the operands to
9183/// facilitate further optimization.
9184Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9185 Value *FalseVal) {
9186 // See the comment above GetSelectFoldableOperands for a description of the
9187 // transformation we are doing here.
9188 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9189 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9190 !isa<Constant>(FalseVal)) {
9191 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9192 unsigned OpToFold = 0;
9193 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9194 OpToFold = 1;
9195 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9196 OpToFold = 2;
9197 }
9198
9199 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009200 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009201 Value *OOp = TVI->getOperand(2-OpToFold);
9202 // Avoid creating select between 2 constants unless it's selecting
9203 // between 0 and 1.
9204 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9205 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9206 InsertNewInstBefore(NewSel, SI);
9207 NewSel->takeName(TVI);
9208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9209 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009210 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009211 }
9212 }
9213 }
9214 }
9215 }
9216
9217 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9218 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9219 !isa<Constant>(TrueVal)) {
9220 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9221 unsigned OpToFold = 0;
9222 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9223 OpToFold = 1;
9224 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9225 OpToFold = 2;
9226 }
9227
9228 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009229 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009230 Value *OOp = FVI->getOperand(2-OpToFold);
9231 // Avoid creating select between 2 constants unless it's selecting
9232 // between 0 and 1.
9233 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9234 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9235 InsertNewInstBefore(NewSel, SI);
9236 NewSel->takeName(FVI);
9237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9238 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009239 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009240 }
9241 }
9242 }
9243 }
9244 }
9245
9246 return 0;
9247}
9248
Dan Gohman81b28ce2008-09-16 18:46:06 +00009249/// visitSelectInstWithICmp - Visit a SelectInst that has an
9250/// ICmpInst as its first operand.
9251///
9252Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9253 ICmpInst *ICI) {
9254 bool Changed = false;
9255 ICmpInst::Predicate Pred = ICI->getPredicate();
9256 Value *CmpLHS = ICI->getOperand(0);
9257 Value *CmpRHS = ICI->getOperand(1);
9258 Value *TrueVal = SI.getTrueValue();
9259 Value *FalseVal = SI.getFalseValue();
9260
9261 // Check cases where the comparison is with a constant that
9262 // can be adjusted to fit the min/max idiom. We may edit ICI in
9263 // place here, so make sure the select is the only user.
9264 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009265 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009266 switch (Pred) {
9267 default: break;
9268 case ICmpInst::ICMP_ULT:
9269 case ICmpInst::ICMP_SLT: {
9270 // X < MIN ? T : F --> F
9271 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9272 return ReplaceInstUsesWith(SI, FalseVal);
9273 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009274 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009275 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9276 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9277 Pred = ICmpInst::getSwappedPredicate(Pred);
9278 CmpRHS = AdjustedRHS;
9279 std::swap(FalseVal, TrueVal);
9280 ICI->setPredicate(Pred);
9281 ICI->setOperand(1, CmpRHS);
9282 SI.setOperand(1, TrueVal);
9283 SI.setOperand(2, FalseVal);
9284 Changed = true;
9285 }
9286 break;
9287 }
9288 case ICmpInst::ICMP_UGT:
9289 case ICmpInst::ICMP_SGT: {
9290 // X > MAX ? T : F --> F
9291 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9292 return ReplaceInstUsesWith(SI, FalseVal);
9293 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009294 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009295 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9296 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9297 Pred = ICmpInst::getSwappedPredicate(Pred);
9298 CmpRHS = AdjustedRHS;
9299 std::swap(FalseVal, TrueVal);
9300 ICI->setPredicate(Pred);
9301 ICI->setOperand(1, CmpRHS);
9302 SI.setOperand(1, TrueVal);
9303 SI.setOperand(2, FalseVal);
9304 Changed = true;
9305 }
9306 break;
9307 }
9308 }
9309
Dan Gohman1975d032008-10-30 20:40:10 +00009310 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9311 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009312 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009313 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9314 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009315 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009316 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9317 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009318 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9319
Dan Gohman1975d032008-10-30 20:40:10 +00009320 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9321 // If we are just checking for a icmp eq of a single bit and zext'ing it
9322 // to an integer, then shift the bit to the appropriate place and then
9323 // cast to integer to avoid the comparison.
9324 const APInt &Op1CV = CI->getValue();
9325
9326 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9327 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9328 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009329 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009330 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009331 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009332 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009333 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009334 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009335 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009336 if (In->getType() != SI.getType())
9337 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009338 true/*SExt*/, "tmp", ICI);
9339
9340 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009341 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009342 In->getName()+".not"), *ICI);
9343
9344 return ReplaceInstUsesWith(SI, In);
9345 }
9346 }
9347 }
9348
Dan Gohman81b28ce2008-09-16 18:46:06 +00009349 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9350 // Transform (X == Y) ? X : Y -> Y
9351 if (Pred == ICmpInst::ICMP_EQ)
9352 return ReplaceInstUsesWith(SI, FalseVal);
9353 // Transform (X != Y) ? X : Y -> X
9354 if (Pred == ICmpInst::ICMP_NE)
9355 return ReplaceInstUsesWith(SI, TrueVal);
9356 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9357
9358 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9359 // Transform (X == Y) ? Y : X -> X
9360 if (Pred == ICmpInst::ICMP_EQ)
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 // Transform (X != Y) ? Y : X -> Y
9363 if (Pred == ICmpInst::ICMP_NE)
9364 return ReplaceInstUsesWith(SI, TrueVal);
9365 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9366 }
9367
9368 /// NOTE: if we wanted to, this is where to detect integer ABS
9369
9370 return Changed ? &SI : 0;
9371}
9372
Chris Lattner3d69f462004-03-12 05:52:32 +00009373Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009374 Value *CondVal = SI.getCondition();
9375 Value *TrueVal = SI.getTrueValue();
9376 Value *FalseVal = SI.getFalseValue();
9377
9378 // select true, X, Y -> X
9379 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009380 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009381 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009382
9383 // select C, X, X -> X
9384 if (TrueVal == FalseVal)
9385 return ReplaceInstUsesWith(SI, TrueVal);
9386
Chris Lattnere87597f2004-10-16 18:11:37 +00009387 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9388 return ReplaceInstUsesWith(SI, FalseVal);
9389 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9390 return ReplaceInstUsesWith(SI, TrueVal);
9391 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9392 if (isa<Constant>(TrueVal))
9393 return ReplaceInstUsesWith(SI, TrueVal);
9394 else
9395 return ReplaceInstUsesWith(SI, FalseVal);
9396 }
9397
Reid Spencer4fe16d62007-01-11 18:21:29 +00009398 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009399 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009400 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009401 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009402 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009403 } else {
9404 // Change: A = select B, false, C --> A = and !B, C
9405 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009406 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009407 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009409 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009410 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009411 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009412 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009413 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009414 } else {
9415 // Change: A = select B, C, true --> A = or !B, C
9416 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009417 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009418 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009419 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009420 }
9421 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009422
9423 // select a, b, a -> a&b
9424 // select a, a, b -> a|b
9425 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009426 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009427 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009428 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009429 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009430
Chris Lattner2eefe512004-04-09 19:05:30 +00009431 // Selecting between two integer constants?
9432 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9433 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009434 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009435 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009436 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009437 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009438 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009439 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009440 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009441 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009442 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009443 }
Chris Lattner457dd822004-06-09 07:59:58 +00009444
Reid Spencere4d87aa2006-12-23 06:05:41 +00009445 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009446 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009447 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009448 // non-constant value, eliminate this whole mess. This corresponds to
9449 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009450 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009451 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009452 cast<Constant>(IC->getOperand(1))->isNullValue())
9453 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9454 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009455 isa<ConstantInt>(ICA->getOperand(1)) &&
9456 (ICA->getOperand(1) == TrueValC ||
9457 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009458 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9459 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009460 // know whether we have a icmp_ne or icmp_eq and whether the
9461 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009462 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009463 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009464 Value *V = ICA;
9465 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009466 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009467 Instruction::Xor, V, ICA->getOperand(1)), SI);
9468 return ReplaceInstUsesWith(SI, V);
9469 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009470 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009471 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009472
9473 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009474 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9475 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009476 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009477 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9478 // This is not safe in general for floating point:
9479 // consider X== -0, Y== +0.
9480 // It becomes safe if either operand is a nonzero constant.
9481 ConstantFP *CFPt, *CFPf;
9482 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9483 !CFPt->getValueAPF().isZero()) ||
9484 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9485 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009486 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009487 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009488 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009489 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009490 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009491 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009492
Reid Spencere4d87aa2006-12-23 06:05:41 +00009493 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009494 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009495 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9496 // This is not safe in general for floating point:
9497 // consider X== -0, Y== +0.
9498 // It becomes safe if either operand is a nonzero constant.
9499 ConstantFP *CFPt, *CFPf;
9500 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9501 !CFPt->getValueAPF().isZero()) ||
9502 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9503 !CFPf->getValueAPF().isZero()))
9504 return ReplaceInstUsesWith(SI, FalseVal);
9505 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009506 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009507 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9508 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009509 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009510 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009511 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009512 }
9513
9514 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009515 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9516 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9517 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009518
Chris Lattner87875da2005-01-13 22:52:24 +00009519 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9520 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9521 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009522 Instruction *AddOp = 0, *SubOp = 0;
9523
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009524 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9525 if (TI->getOpcode() == FI->getOpcode())
9526 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9527 return IV;
9528
9529 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9530 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009531 if ((TI->getOpcode() == Instruction::Sub &&
9532 FI->getOpcode() == Instruction::Add) ||
9533 (TI->getOpcode() == Instruction::FSub &&
9534 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009535 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009536 } else if ((FI->getOpcode() == Instruction::Sub &&
9537 TI->getOpcode() == Instruction::Add) ||
9538 (FI->getOpcode() == Instruction::FSub &&
9539 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009540 AddOp = TI; SubOp = FI;
9541 }
9542
9543 if (AddOp) {
9544 Value *OtherAddOp = 0;
9545 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9546 OtherAddOp = AddOp->getOperand(1);
9547 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9548 OtherAddOp = AddOp->getOperand(0);
9549 }
9550
9551 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009552 // So at this point we know we have (Y -> OtherAddOp):
9553 // select C, (add X, Y), (sub X, Z)
9554 Value *NegVal; // Compute -Z
9555 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009556 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009557 } else {
9558 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009559 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9560 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009561 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009562
9563 Value *NewTrueOp = OtherAddOp;
9564 Value *NewFalseOp = NegVal;
9565 if (AddOp != TI)
9566 std::swap(NewTrueOp, NewFalseOp);
9567 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009568 SelectInst::Create(CondVal, NewTrueOp,
9569 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009570
9571 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009572 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009573 }
9574 }
9575 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009576
Chris Lattnere576b912004-04-09 23:46:01 +00009577 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009578 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009579 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9580 if (FoldI)
9581 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009582 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009583
9584 if (BinaryOperator::isNot(CondVal)) {
9585 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9586 SI.setOperand(1, FalseVal);
9587 SI.setOperand(2, TrueVal);
9588 return &SI;
9589 }
9590
Chris Lattner3d69f462004-03-12 05:52:32 +00009591 return 0;
9592}
9593
Dan Gohmaneee962e2008-04-10 18:43:06 +00009594/// EnforceKnownAlignment - If the specified pointer points to an object that
9595/// we control, modify the object's alignment to PrefAlign. This isn't
9596/// often possible though. If alignment is important, a more reliable approach
9597/// is to simply align all global variables and allocation instructions to
9598/// their preferred alignment from the beginning.
9599///
9600static unsigned EnforceKnownAlignment(Value *V,
9601 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009602
Dan Gohmaneee962e2008-04-10 18:43:06 +00009603 User *U = dyn_cast<User>(V);
9604 if (!U) return Align;
9605
Dan Gohmanca178902009-07-17 20:47:02 +00009606 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009607 default: break;
9608 case Instruction::BitCast:
9609 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9610 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009611 // If all indexes are zero, it is just the alignment of the base pointer.
9612 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009613 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009614 if (!isa<Constant>(*i) ||
9615 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009616 AllZeroOperands = false;
9617 break;
9618 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009619
9620 if (AllZeroOperands) {
9621 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009622 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009623 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009624 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009625 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009626 }
9627
9628 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9629 // If there is a large requested alignment and we can, bump up the alignment
9630 // of the global.
9631 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009632 if (GV->getAlignment() >= PrefAlign)
9633 Align = GV->getAlignment();
9634 else {
9635 GV->setAlignment(PrefAlign);
9636 Align = PrefAlign;
9637 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009638 }
9639 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9640 // If there is a requested alignment and if this is an alloca, round up. We
9641 // don't do this for malloc, because some systems can't respect the request.
9642 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009643 if (AI->getAlignment() >= PrefAlign)
9644 Align = AI->getAlignment();
9645 else {
9646 AI->setAlignment(PrefAlign);
9647 Align = PrefAlign;
9648 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009649 }
9650 }
9651
9652 return Align;
9653}
9654
9655/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9656/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9657/// and it is more than the alignment of the ultimate object, see if we can
9658/// increase the alignment of the ultimate object, making this check succeed.
9659unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9660 unsigned PrefAlign) {
9661 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9662 sizeof(PrefAlign) * CHAR_BIT;
9663 APInt Mask = APInt::getAllOnesValue(BitWidth);
9664 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9665 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9666 unsigned TrailZ = KnownZero.countTrailingOnes();
9667 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9668
9669 if (PrefAlign > Align)
9670 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9671
9672 // We don't need to make any adjustment.
9673 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009674}
9675
Chris Lattnerf497b022008-01-13 23:50:23 +00009676Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009677 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009678 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009679 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009680 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009681
9682 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009683 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009684 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009685 return MI;
9686 }
9687
9688 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9689 // load/store.
9690 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9691 if (MemOpLength == 0) return 0;
9692
Chris Lattner37ac6082008-01-14 00:28:35 +00009693 // Source and destination pointer types are always "i8*" for intrinsic. See
9694 // if the size is something we can handle with a single primitive load/store.
9695 // A single load+store correctly handles overlapping memory in the memmove
9696 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009697 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009698 if (Size == 0) return MI; // Delete this mem transfer.
9699
9700 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009701 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009702
Chris Lattner37ac6082008-01-14 00:28:35 +00009703 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009704 Type *NewPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009705 PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009706
9707 // Memcpy forces the use of i8* for the source and destination. That means
9708 // that if you're using memcpy to move one double around, you'll get a cast
9709 // from double* to i8*. We'd much rather use a double load+store rather than
9710 // an i64 load+store, here because this improves the odds that the source or
9711 // dest address will be promotable. See if we can find a better type than the
9712 // integer datatype.
9713 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9714 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009715 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009716 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9717 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009718 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009719 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9720 if (STy->getNumElements() == 1)
9721 SrcETy = STy->getElementType(0);
9722 else
9723 break;
9724 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9725 if (ATy->getNumElements() == 1)
9726 SrcETy = ATy->getElementType();
9727 else
9728 break;
9729 } else
9730 break;
9731 }
9732
Dan Gohman8f8e2692008-05-23 01:52:21 +00009733 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009734 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009735 }
9736 }
9737
9738
Chris Lattnerf497b022008-01-13 23:50:23 +00009739 // If the memcpy/memmove provides better alignment info than we can
9740 // infer, use it.
9741 SrcAlign = std::max(SrcAlign, CopyAlign);
9742 DstAlign = std::max(DstAlign, CopyAlign);
9743
9744 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9745 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009746 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9747 InsertNewInstBefore(L, *MI);
9748 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9749
9750 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009751 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009752 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009753}
Chris Lattner3d69f462004-03-12 05:52:32 +00009754
Chris Lattner69ea9d22008-04-30 06:39:11 +00009755Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9756 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009757 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009758 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009759 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009760 return MI;
9761 }
9762
9763 // Extract the length and alignment and fill if they are constant.
9764 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9765 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9766 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9767 return 0;
9768 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009769 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009770
9771 // If the length is zero, this is a no-op
9772 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9773
9774 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9775 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersondebcb012009-07-29 22:17:13 +00009776 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009777
9778 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009779 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009780
9781 // Alignment 0 is identity for alignment 1 for memset, but not store.
9782 if (Alignment == 0) Alignment = 1;
9783
9784 // Extract the fill value and store.
9785 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009786 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009787 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788
9789 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009790 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009791 return MI;
9792 }
9793
9794 return 0;
9795}
9796
9797
Chris Lattner8b0ea312006-01-13 20:11:04 +00009798/// visitCallInst - CallInst simplification. This mostly only handles folding
9799/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9800/// the heavy lifting.
9801///
Chris Lattner9fe38862003-06-19 17:00:31 +00009802Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009803 // If the caller function is nounwind, mark the call as nounwind, even if the
9804 // callee isn't.
9805 if (CI.getParent()->getParent()->doesNotThrow() &&
9806 !CI.doesNotThrow()) {
9807 CI.setDoesNotThrow();
9808 return &CI;
9809 }
9810
9811
9812
Chris Lattner8b0ea312006-01-13 20:11:04 +00009813 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9814 if (!II) return visitCallSite(&CI);
9815
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009816 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9817 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009818 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009819 bool Changed = false;
9820
9821 // memmove/cpy/set of zero bytes is a noop.
9822 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9823 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9824
Chris Lattner35b9e482004-10-12 04:52:52 +00009825 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009826 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009827 // Replace the instruction with just byte operations. We would
9828 // transform other cases to loads/stores, but we don't know if
9829 // alignment is sufficient.
9830 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009831 }
9832
Chris Lattner35b9e482004-10-12 04:52:52 +00009833 // If we have a memmove and the source operation is a constant global,
9834 // then the source and dest pointers can't alias, so we can change this
9835 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009836 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009837 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9838 if (GVSrc->isConstant()) {
9839 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009840 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9841 const Type *Tys[1];
9842 Tys[0] = CI.getOperand(3)->getType();
9843 CI.setOperand(0,
9844 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009845 Changed = true;
9846 }
Chris Lattnera935db82008-05-28 05:30:41 +00009847
9848 // memmove(x,x,size) -> noop.
9849 if (MMI->getSource() == MMI->getDest())
9850 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009851 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009852
Chris Lattner95a959d2006-03-06 20:18:44 +00009853 // If we can determine a pointer alignment that is bigger than currently
9854 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009855 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009856 if (Instruction *I = SimplifyMemTransfer(MI))
9857 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009858 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9859 if (Instruction *I = SimplifyMemSet(MSI))
9860 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009861 }
9862
Chris Lattner8b0ea312006-01-13 20:11:04 +00009863 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 }
9865
9866 switch (II->getIntrinsicID()) {
9867 default: break;
9868 case Intrinsic::bswap:
9869 // bswap(bswap(x)) -> x
9870 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9871 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9872 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9873 break;
9874 case Intrinsic::ppc_altivec_lvx:
9875 case Intrinsic::ppc_altivec_lvxl:
9876 case Intrinsic::x86_sse_loadu_ps:
9877 case Intrinsic::x86_sse2_loadu_pd:
9878 case Intrinsic::x86_sse2_loadu_dq:
9879 // Turn PPC lvx -> load if the pointer is known aligned.
9880 // Turn X86 loadups -> load if the pointer is known aligned.
9881 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9882 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009883 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009884 CI);
9885 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009886 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009887 break;
9888 case Intrinsic::ppc_altivec_stvx:
9889 case Intrinsic::ppc_altivec_stvxl:
9890 // Turn stvx -> store if the pointer is known aligned.
9891 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9892 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009893 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009894 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9895 return new StoreInst(II->getOperand(1), Ptr);
9896 }
9897 break;
9898 case Intrinsic::x86_sse_storeu_ps:
9899 case Intrinsic::x86_sse2_storeu_pd:
9900 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009901 // Turn X86 storeu -> store if the pointer is known aligned.
9902 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9903 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009904 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009905 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9906 return new StoreInst(II->getOperand(2), Ptr);
9907 }
9908 break;
9909
9910 case Intrinsic::x86_sse_cvttss2si: {
9911 // These intrinsics only demands the 0th element of its input vector. If
9912 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009913 unsigned VWidth =
9914 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9915 APInt DemandedElts(VWidth, 1);
9916 APInt UndefElts(VWidth, 0);
9917 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009918 UndefElts)) {
9919 II->setOperand(1, V);
9920 return II;
9921 }
9922 break;
9923 }
9924
9925 case Intrinsic::ppc_altivec_vperm:
9926 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9927 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9928 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009929
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 // Check that all of the elements are integer constants or undefs.
9931 bool AllEltsOk = true;
9932 for (unsigned i = 0; i != 16; ++i) {
9933 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9934 !isa<UndefValue>(Mask->getOperand(i))) {
9935 AllEltsOk = false;
9936 break;
9937 }
9938 }
9939
9940 if (AllEltsOk) {
9941 // Cast the input vectors to byte vectors.
9942 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9943 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009944 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009945
Chris Lattner0521e3c2008-06-18 04:33:20 +00009946 // Only extract each element once.
9947 Value *ExtractedElts[32];
9948 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9949
Chris Lattnere2ed0572006-04-06 19:19:17 +00009950 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009951 if (isa<UndefValue>(Mask->getOperand(i)))
9952 continue;
9953 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9954 Idx &= 31; // Match the hardware behavior.
9955
9956 if (ExtractedElts[Idx] == 0) {
9957 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009958 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneed707b2009-07-24 23:12:02 +00009959 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009960 InsertNewInstBefore(Elt, CI);
9961 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009962 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009963
Chris Lattner0521e3c2008-06-18 04:33:20 +00009964 // Insert this value into the result vector.
9965 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneed707b2009-07-24 23:12:02 +00009966 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009967 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009968 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009969 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009970 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009971 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972 }
9973 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009974
Chris Lattner0521e3c2008-06-18 04:33:20 +00009975 case Intrinsic::stackrestore: {
9976 // If the save is right next to the restore, remove the restore. This can
9977 // happen when variable allocas are DCE'd.
9978 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9979 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9980 BasicBlock::iterator BI = SS;
9981 if (&*++BI == II)
9982 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009983 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009984 }
9985
9986 // Scan down this block to see if there is another stack restore in the
9987 // same block without an intervening call/alloca.
9988 BasicBlock::iterator BI = II;
9989 TerminatorInst *TI = II->getParent()->getTerminator();
9990 bool CannotRemove = false;
9991 for (++BI; &*BI != TI; ++BI) {
9992 if (isa<AllocaInst>(BI)) {
9993 CannotRemove = true;
9994 break;
9995 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009996 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9997 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9998 // If there is a stackrestore below this one, remove this one.
9999 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10000 return EraseInstFromFunction(CI);
10001 // Otherwise, ignore the intrinsic.
10002 } else {
10003 // If we found a non-intrinsic call, we can't remove the stack
10004 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010005 CannotRemove = true;
10006 break;
10007 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010008 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010009 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010010
10011 // If the stack restore is in a return/unwind block and if there are no
10012 // allocas or calls between the restore and the return, nuke the restore.
10013 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10014 return EraseInstFromFunction(CI);
10015 break;
10016 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010017 }
10018
Chris Lattner8b0ea312006-01-13 20:11:04 +000010019 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010020}
10021
10022// InvokeInst simplification
10023//
10024Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010025 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010026}
10027
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010028/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10029/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010030static bool isSafeToEliminateVarargsCast(const CallSite CS,
10031 const CastInst * const CI,
10032 const TargetData * const TD,
10033 const int ix) {
10034 if (!CI->isLosslessCast())
10035 return false;
10036
10037 // The size of ByVal arguments is derived from the type, so we
10038 // can't change to a type with a different size. If the size were
10039 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010040 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010041 return true;
10042
10043 const Type* SrcTy =
10044 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10045 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10046 if (!SrcTy->isSized() || !DstTy->isSized())
10047 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010048 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010049 return false;
10050 return true;
10051}
10052
Chris Lattnera44d8a22003-10-07 22:32:43 +000010053// visitCallSite - Improvements for call and invoke instructions.
10054//
10055Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010056 bool Changed = false;
10057
10058 // If the callee is a constexpr cast of a function, attempt to move the cast
10059 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010060 if (transformConstExprCastCall(CS)) return 0;
10061
Chris Lattner6c266db2003-10-07 22:54:13 +000010062 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010063
Chris Lattner08b22ec2005-05-13 07:09:09 +000010064 if (Function *CalleeF = dyn_cast<Function>(Callee))
10065 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10066 Instruction *OldCall = CS.getInstruction();
10067 // If the call and callee calling conventions don't match, this call must
10068 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010069 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010070 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010071 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010072 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010073 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010074 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10075 return EraseInstFromFunction(*OldCall);
10076 return 0;
10077 }
10078
Chris Lattner17be6352004-10-18 02:59:09 +000010079 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10080 // This instruction is not reachable, just remove it. We insert a store to
10081 // undef so that we know that this code is not reachable, despite the fact
10082 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010083 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010084 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010085 CS.getInstruction());
10086
10087 if (!CS.getInstruction()->use_empty())
10088 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010089 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010090
10091 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10092 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010093 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010094 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010095 }
Chris Lattner17be6352004-10-18 02:59:09 +000010096 return EraseInstFromFunction(*CS.getInstruction());
10097 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010098
Duncan Sandscdb6d922007-09-17 10:26:40 +000010099 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10100 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10101 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10102 return transformCallThroughTrampoline(CS);
10103
Chris Lattner6c266db2003-10-07 22:54:13 +000010104 const PointerType *PTy = cast<PointerType>(Callee->getType());
10105 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10106 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010107 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010108 // See if we can optimize any arguments passed through the varargs area of
10109 // the call.
10110 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010111 E = CS.arg_end(); I != E; ++I, ++ix) {
10112 CastInst *CI = dyn_cast<CastInst>(*I);
10113 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10114 *I = CI->getOperand(0);
10115 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010116 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010117 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010118 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010119
Duncan Sandsf0c33542007-12-19 21:13:37 +000010120 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010121 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010122 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010123 Changed = true;
10124 }
10125
Chris Lattner6c266db2003-10-07 22:54:13 +000010126 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010127}
10128
Chris Lattner9fe38862003-06-19 17:00:31 +000010129// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10130// attempt to move the cast to the arguments of the call/invoke.
10131//
10132bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10133 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10134 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010135 if (CE->getOpcode() != Instruction::BitCast ||
10136 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010137 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010138 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010139 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010140 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010141
10142 // Okay, this is a cast from a function to a different type. Unless doing so
10143 // would cause a type conversion of one of our arguments, change this call to
10144 // be a direct call with arguments casted to the appropriate types.
10145 //
10146 const FunctionType *FT = Callee->getFunctionType();
10147 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010148 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010149
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010150 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010151 return false; // TODO: Handle multiple return values.
10152
Chris Lattnerf78616b2004-01-14 06:06:08 +000010153 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010154 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010155 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010156 // Conversion is ok if changing from one pointer type to another or from
10157 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010158 !((isa<PointerType>(OldRetTy) || !TD ||
10159 OldRetTy == TD->getIntPtrType()) &&
10160 (isa<PointerType>(NewRetTy) || !TD ||
10161 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010162 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010163
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010164 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010165 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010166 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010167 return false; // Cannot transform this return value.
10168
Chris Lattner58d74912008-03-12 17:45:29 +000010169 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010170 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010171 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010172 return false; // Attribute not compatible with transformed value.
10173 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010174
Chris Lattnerf78616b2004-01-14 06:06:08 +000010175 // If the callsite is an invoke instruction, and the return value is used by
10176 // a PHI node in a successor, we cannot change the return type of the call
10177 // because there is no place to put the cast instruction (without breaking
10178 // the critical edge). Bail out in this case.
10179 if (!Caller->use_empty())
10180 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10181 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10182 UI != E; ++UI)
10183 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10184 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010185 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010186 return false;
10187 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010188
10189 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10190 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010191
Chris Lattner9fe38862003-06-19 17:00:31 +000010192 CallSite::arg_iterator AI = CS.arg_begin();
10193 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10194 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010195 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010196
10197 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010198 return false; // Cannot transform this parameter value.
10199
Devang Patel19c87462008-09-26 22:53:05 +000010200 if (CallerPAL.getParamAttributes(i + 1)
10201 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010202 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010203
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010204 // Converting from one pointer type to another or between a pointer and an
10205 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010206 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010207 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10208 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010209 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010210 }
10211
10212 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010213 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010214 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010215
Chris Lattner58d74912008-03-12 17:45:29 +000010216 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10217 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010218 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010219 // won't be dropping them. Check that these extra arguments have attributes
10220 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010221 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10222 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010223 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010224 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010225 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010226 return false;
10227 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010228
Chris Lattner9fe38862003-06-19 17:00:31 +000010229 // Okay, we decided that this is a safe thing to do: go ahead and start
10230 // inserting cast instructions as necessary...
10231 std::vector<Value*> Args;
10232 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010233 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010234 attrVec.reserve(NumCommonArgs);
10235
10236 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010237 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010238
10239 // If the return value is not being used, the type may not be compatible
10240 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010241 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010242
10243 // Add the new return attributes.
10244 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010245 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010246
10247 AI = CS.arg_begin();
10248 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10249 const Type *ParamTy = FT->getParamType(i);
10250 if ((*AI)->getType() == ParamTy) {
10251 Args.push_back(*AI);
10252 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010253 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010254 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010255 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010256 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010257 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010258
10259 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010260 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010261 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010262 }
10263
10264 // If the function takes more arguments than the call was taking, add them
10265 // now...
10266 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010267 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010268
10269 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010270 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010271 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010272 errs() << "WARNING: While resolving call to function '"
10273 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010274 } else {
10275 // Add all of the arguments in their promoted form to the arg list...
10276 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10277 const Type *PTy = getPromotedType((*AI)->getType());
10278 if (PTy != (*AI)->getType()) {
10279 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010280 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10281 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010282 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010283 InsertNewInstBefore(Cast, *Caller);
10284 Args.push_back(Cast);
10285 } else {
10286 Args.push_back(*AI);
10287 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010288
Duncan Sandse1e520f2008-01-13 08:02:44 +000010289 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010290 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010291 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010292 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010293 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010294 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010295
Devang Patel19c87462008-09-26 22:53:05 +000010296 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10297 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10298
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010299 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010300 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010301
Eric Christophera66297a2009-07-25 02:45:27 +000010302 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10303 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010304
Chris Lattner9fe38862003-06-19 17:00:31 +000010305 Instruction *NC;
10306 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010307 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010308 Args.begin(), Args.end(),
10309 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010310 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010311 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010313 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10314 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010315 CallInst *CI = cast<CallInst>(Caller);
10316 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010317 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010318 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010319 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010320 }
10321
Chris Lattner6934a042007-02-11 01:23:03 +000010322 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010323 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010324 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010325 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010326 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010327 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010328 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010329
10330 // If this is an invoke instruction, we should insert it after the first
10331 // non-phi, instruction in the normal successor block.
10332 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010333 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010334 InsertNewInstBefore(NC, *I);
10335 } else {
10336 // Otherwise, it's a call, just insert cast right after the call instr
10337 InsertNewInstBefore(NC, *Caller);
10338 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010339 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010340 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010341 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010342 }
10343 }
10344
10345 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10346 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010347 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010348 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010349 return true;
10350}
10351
Duncan Sandscdb6d922007-09-17 10:26:40 +000010352// transformCallThroughTrampoline - Turn a call to a function created by the
10353// init_trampoline intrinsic into a direct call to the underlying function.
10354//
10355Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10356 Value *Callee = CS.getCalledValue();
10357 const PointerType *PTy = cast<PointerType>(Callee->getType());
10358 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010359 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010360
10361 // If the call already has the 'nest' attribute somewhere then give up -
10362 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010363 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010364 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365
10366 IntrinsicInst *Tramp =
10367 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10368
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010369 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010370 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10371 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10372
Devang Patel05988662008-09-25 21:00:45 +000010373 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010374 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375 unsigned NestIdx = 1;
10376 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010377 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378
10379 // Look for a parameter marked with the 'nest' attribute.
10380 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10381 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010382 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 // Record the parameter type and any other attributes.
10384 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010385 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 break;
10387 }
10388
10389 if (NestTy) {
10390 Instruction *Caller = CS.getInstruction();
10391 std::vector<Value*> NewArgs;
10392 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10393
Devang Patel05988662008-09-25 21:00:45 +000010394 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010395 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010396
Duncan Sandscdb6d922007-09-17 10:26:40 +000010397 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010398 // mean appending it. Likewise for attributes.
10399
Devang Patel19c87462008-09-26 22:53:05 +000010400 // Add any result attributes.
10401 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010402 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010403
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 {
10405 unsigned Idx = 1;
10406 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10407 do {
10408 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010409 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410 Value *NestVal = Tramp->getOperand(3);
10411 if (NestVal->getType() != NestTy)
10412 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10413 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010414 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010415 }
10416
10417 if (I == E)
10418 break;
10419
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010420 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010422 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010423 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010424 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010425
10426 ++Idx, ++I;
10427 } while (1);
10428 }
10429
Devang Patel19c87462008-09-26 22:53:05 +000010430 // Add any function attributes.
10431 if (Attributes Attr = Attrs.getFnAttributes())
10432 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10433
Duncan Sandscdb6d922007-09-17 10:26:40 +000010434 // The trampoline may have been bitcast to a bogus type (FTy).
10435 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010436 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010437
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010439 NewTypes.reserve(FTy->getNumParams()+1);
10440
Duncan Sandscdb6d922007-09-17 10:26:40 +000010441 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010442 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 {
10444 unsigned Idx = 1;
10445 FunctionType::param_iterator I = FTy->param_begin(),
10446 E = FTy->param_end();
10447
10448 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010449 if (Idx == NestIdx)
10450 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010451 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452
10453 if (I == E)
10454 break;
10455
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010456 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010458
10459 ++Idx, ++I;
10460 } while (1);
10461 }
10462
10463 // Replace the trampoline call with a direct call. Let the generic
10464 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010465 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010466 FTy->isVarArg());
10467 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010468 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010469 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010470 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010471 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10472 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010473
10474 Instruction *NewCaller;
10475 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010476 NewCaller = InvokeInst::Create(NewCallee,
10477 II->getNormalDest(), II->getUnwindDest(),
10478 NewArgs.begin(), NewArgs.end(),
10479 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010480 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010481 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010483 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10484 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010485 if (cast<CallInst>(Caller)->isTailCall())
10486 cast<CallInst>(NewCaller)->setTailCall();
10487 cast<CallInst>(NewCaller)->
10488 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010489 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010490 }
10491 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10492 Caller->replaceAllUsesWith(NewCaller);
10493 Caller->eraseFromParent();
10494 RemoveFromWorkList(Caller);
10495 return 0;
10496 }
10497 }
10498
10499 // Replace the trampoline call with a direct call. Since there is no 'nest'
10500 // parameter, there is no need to adjust the argument list. Let the generic
10501 // code sort out any function type mismatches.
10502 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010503 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010504 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010505 CS.setCalledFunction(NewCallee);
10506 return CS.getInstruction();
10507}
10508
Chris Lattner7da52b22006-11-01 04:51:18 +000010509/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10510/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10511/// and a single binop.
10512Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10513 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010514 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010515 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010516 Value *LHSVal = FirstInst->getOperand(0);
10517 Value *RHSVal = FirstInst->getOperand(1);
10518
10519 const Type *LHSType = LHSVal->getType();
10520 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010521
10522 // Scan to see if all operands are the same opcode, all have one use, and all
10523 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010524 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010525 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010526 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010527 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010528 // types or GEP's with different index types.
10529 I->getOperand(0)->getType() != LHSType ||
10530 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010531 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010532
10533 // If they are CmpInst instructions, check their predicates
10534 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10535 if (cast<CmpInst>(I)->getPredicate() !=
10536 cast<CmpInst>(FirstInst)->getPredicate())
10537 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010538
10539 // Keep track of which operand needs a phi node.
10540 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10541 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010542 }
10543
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010544 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010545
Chris Lattner7da52b22006-11-01 04:51:18 +000010546 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010547 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010548 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010549 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010550 NewLHS = PHINode::Create(LHSType,
10551 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010552 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10553 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010554 InsertNewInstBefore(NewLHS, PN);
10555 LHSVal = NewLHS;
10556 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010557
10558 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010559 NewRHS = PHINode::Create(RHSType,
10560 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010561 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10562 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010563 InsertNewInstBefore(NewRHS, PN);
10564 RHSVal = NewRHS;
10565 }
10566
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010567 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010568 if (NewLHS || NewRHS) {
10569 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10570 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10571 if (NewLHS) {
10572 Value *NewInLHS = InInst->getOperand(0);
10573 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10574 }
10575 if (NewRHS) {
10576 Value *NewInRHS = InInst->getOperand(1);
10577 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10578 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010579 }
10580 }
10581
Chris Lattner7da52b22006-11-01 04:51:18 +000010582 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010583 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010584 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010585 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10586 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010587}
10588
Chris Lattner05f18922008-12-01 02:34:36 +000010589Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10590 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10591
10592 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10593 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010594 // This is true if all GEP bases are allocas and if all indices into them are
10595 // constants.
10596 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010597
10598 // Scan to see if all operands are the same opcode, all have one use, and all
10599 // kill their operands (i.e. the operands have one use).
10600 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10601 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10602 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10603 GEP->getNumOperands() != FirstInst->getNumOperands())
10604 return 0;
10605
Chris Lattner36d3e322009-02-21 00:46:50 +000010606 // Keep track of whether or not all GEPs are of alloca pointers.
10607 if (AllBasePointersAreAllocas &&
10608 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10609 !GEP->hasAllConstantIndices()))
10610 AllBasePointersAreAllocas = false;
10611
Chris Lattner05f18922008-12-01 02:34:36 +000010612 // Compare the operand lists.
10613 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10614 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10615 continue;
10616
10617 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10618 // if one of the PHIs has a constant for the index. The index may be
10619 // substantially cheaper to compute for the constants, so making it a
10620 // variable index could pessimize the path. This also handles the case
10621 // for struct indices, which must always be constant.
10622 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10623 isa<ConstantInt>(GEP->getOperand(op)))
10624 return 0;
10625
10626 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10627 return 0;
10628 FixedOperands[op] = 0; // Needs a PHI.
10629 }
10630 }
10631
Chris Lattner36d3e322009-02-21 00:46:50 +000010632 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010633 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010634 // offset calculation, but all the predecessors will have to materialize the
10635 // stack address into a register anyway. We'd actually rather *clone* the
10636 // load up into the predecessors so that we have a load of a gep of an alloca,
10637 // which can usually all be folded into the load.
10638 if (AllBasePointersAreAllocas)
10639 return 0;
10640
Chris Lattner05f18922008-12-01 02:34:36 +000010641 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10642 // that is variable.
10643 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10644
10645 bool HasAnyPHIs = false;
10646 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10647 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10648 Value *FirstOp = FirstInst->getOperand(i);
10649 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10650 FirstOp->getName()+".pn");
10651 InsertNewInstBefore(NewPN, PN);
10652
10653 NewPN->reserveOperandSpace(e);
10654 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10655 OperandPhis[i] = NewPN;
10656 FixedOperands[i] = NewPN;
10657 HasAnyPHIs = true;
10658 }
10659
10660
10661 // Add all operands to the new PHIs.
10662 if (HasAnyPHIs) {
10663 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10664 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10665 BasicBlock *InBB = PN.getIncomingBlock(i);
10666
10667 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10668 if (PHINode *OpPhi = OperandPhis[op])
10669 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10670 }
10671 }
10672
10673 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010674 GetElementPtrInst *GEP =
10675 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10676 FixedOperands.end());
10677 if (cast<GEPOperator>(FirstInst)->isInBounds())
10678 cast<GEPOperator>(GEP)->setIsInBounds(true);
10679 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010680}
10681
10682
Chris Lattner21550882009-02-23 05:56:17 +000010683/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10684/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010685/// obvious the value of the load is not changed from the point of the load to
10686/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010687///
10688/// Finally, it is safe, but not profitable, to sink a load targetting a
10689/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10690/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010691static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010692 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10693
10694 for (++BBI; BBI != E; ++BBI)
10695 if (BBI->mayWriteToMemory())
10696 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010697
10698 // Check for non-address taken alloca. If not address-taken already, it isn't
10699 // profitable to do this xform.
10700 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10701 bool isAddressTaken = false;
10702 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10703 UI != E; ++UI) {
10704 if (isa<LoadInst>(UI)) continue;
10705 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10706 // If storing TO the alloca, then the address isn't taken.
10707 if (SI->getOperand(1) == AI) continue;
10708 }
10709 isAddressTaken = true;
10710 break;
10711 }
10712
Chris Lattner36d3e322009-02-21 00:46:50 +000010713 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010714 return false;
10715 }
10716
Chris Lattner36d3e322009-02-21 00:46:50 +000010717 // If this load is a load from a GEP with a constant offset from an alloca,
10718 // then we don't want to sink it. In its present form, it will be
10719 // load [constant stack offset]. Sinking it will cause us to have to
10720 // materialize the stack addresses in each predecessor in a register only to
10721 // do a shared load from register in the successor.
10722 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10723 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10724 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10725 return false;
10726
Chris Lattner76c73142006-11-01 07:13:54 +000010727 return true;
10728}
10729
Chris Lattner9fe38862003-06-19 17:00:31 +000010730
Chris Lattnerbac32862004-11-14 19:13:23 +000010731// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10732// operator and they all are only used by the PHI, PHI together their
10733// inputs, and do the operation once, to the result of the PHI.
10734Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10735 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10736
10737 // Scan the instruction, looking for input operations that can be folded away.
10738 // If all input operands to the phi are the same instruction (e.g. a cast from
10739 // the same type or "+42") we can pull the operation through the PHI, reducing
10740 // code size and simplifying code.
10741 Constant *ConstantOp = 0;
10742 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010743 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010744 if (isa<CastInst>(FirstInst)) {
10745 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010746 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010747 // Can fold binop, compare or shift here if the RHS is a constant,
10748 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010749 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010750 if (ConstantOp == 0)
10751 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010752 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10753 isVolatile = LI->isVolatile();
10754 // We can't sink the load if the loaded value could be modified between the
10755 // load and the PHI.
10756 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010757 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010758 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010759
10760 // If the PHI is of volatile loads and the load block has multiple
10761 // successors, sinking it would remove a load of the volatile value from
10762 // the path through the other successor.
10763 if (isVolatile &&
10764 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10765 return 0;
10766
Chris Lattner9c080502006-11-01 07:43:41 +000010767 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010768 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010769 } else {
10770 return 0; // Cannot fold this operation.
10771 }
10772
10773 // Check to see if all arguments are the same operation.
10774 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10775 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10776 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010777 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010778 return 0;
10779 if (CastSrcTy) {
10780 if (I->getOperand(0)->getType() != CastSrcTy)
10781 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010782 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010783 // We can't sink the load if the loaded value could be modified between
10784 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010785 if (LI->isVolatile() != isVolatile ||
10786 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010787 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010788 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010789
Chris Lattner71042962008-07-08 17:18:32 +000010790 // If the PHI is of volatile loads and the load block has multiple
10791 // successors, sinking it would remove a load of the volatile value from
10792 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010793 if (isVolatile &&
10794 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10795 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010796
Chris Lattnerbac32862004-11-14 19:13:23 +000010797 } else if (I->getOperand(1) != ConstantOp) {
10798 return 0;
10799 }
10800 }
10801
10802 // Okay, they are all the same operation. Create a new PHI node of the
10803 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010804 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10805 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010806 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010807
10808 Value *InVal = FirstInst->getOperand(0);
10809 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010810
10811 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010812 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10814 if (NewInVal != InVal)
10815 InVal = 0;
10816 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10817 }
10818
10819 Value *PhiVal;
10820 if (InVal) {
10821 // The new PHI unions all of the same values together. This is really
10822 // common, so we handle it intelligently here for compile-time speed.
10823 PhiVal = InVal;
10824 delete NewPN;
10825 } else {
10826 InsertNewInstBefore(NewPN, PN);
10827 PhiVal = NewPN;
10828 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010829
Chris Lattnerbac32862004-11-14 19:13:23 +000010830 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010831 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010832 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010833 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010834 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010835 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010836 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010837 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010838 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10839
10840 // If this was a volatile load that we are merging, make sure to loop through
10841 // and mark all the input loads as non-volatile. If we don't do this, we will
10842 // insert a new volatile load and the old ones will not be deletable.
10843 if (isVolatile)
10844 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10845 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10846
10847 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010848}
Chris Lattnera1be5662002-05-02 17:06:02 +000010849
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010850/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10851/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010852static bool DeadPHICycle(PHINode *PN,
10853 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010854 if (PN->use_empty()) return true;
10855 if (!PN->hasOneUse()) return false;
10856
10857 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010858 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010859 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010860
10861 // Don't scan crazily complex things.
10862 if (PotentiallyDeadPHIs.size() == 16)
10863 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010864
10865 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10866 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010867
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010868 return false;
10869}
10870
Chris Lattnercf5008a2007-11-06 21:52:06 +000010871/// PHIsEqualValue - Return true if this phi node is always equal to
10872/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10873/// z = some value; x = phi (y, z); y = phi (x, z)
10874static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10875 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10876 // See if we already saw this PHI node.
10877 if (!ValueEqualPHIs.insert(PN))
10878 return true;
10879
10880 // Don't scan crazily complex things.
10881 if (ValueEqualPHIs.size() == 16)
10882 return false;
10883
10884 // Scan the operands to see if they are either phi nodes or are equal to
10885 // the value.
10886 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10887 Value *Op = PN->getIncomingValue(i);
10888 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10889 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10890 return false;
10891 } else if (Op != NonPhiInVal)
10892 return false;
10893 }
10894
10895 return true;
10896}
10897
10898
Chris Lattner473945d2002-05-06 18:06:38 +000010899// PHINode simplification
10900//
Chris Lattner7e708292002-06-25 16:13:24 +000010901Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010902 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010903 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010904
Owen Anderson7e057142006-07-10 22:03:18 +000010905 if (Value *V = PN.hasConstantValue())
10906 return ReplaceInstUsesWith(PN, V);
10907
Owen Anderson7e057142006-07-10 22:03:18 +000010908 // If all PHI operands are the same operation, pull them through the PHI,
10909 // reducing code size.
10910 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010911 isa<Instruction>(PN.getIncomingValue(1)) &&
10912 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10913 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10914 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10915 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010916 PN.getIncomingValue(0)->hasOneUse())
10917 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10918 return Result;
10919
10920 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10921 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10922 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010923 if (PN.hasOneUse()) {
10924 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10925 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010926 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010927 PotentiallyDeadPHIs.insert(&PN);
10928 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010929 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010930 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010931
10932 // If this phi has a single use, and if that use just computes a value for
10933 // the next iteration of a loop, delete the phi. This occurs with unused
10934 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10935 // common case here is good because the only other things that catch this
10936 // are induction variable analysis (sometimes) and ADCE, which is only run
10937 // late.
10938 if (PHIUser->hasOneUse() &&
10939 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10940 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010941 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010942 }
10943 }
Owen Anderson7e057142006-07-10 22:03:18 +000010944
Chris Lattnercf5008a2007-11-06 21:52:06 +000010945 // We sometimes end up with phi cycles that non-obviously end up being the
10946 // same value, for example:
10947 // z = some value; x = phi (y, z); y = phi (x, z)
10948 // where the phi nodes don't necessarily need to be in the same block. Do a
10949 // quick check to see if the PHI node only contains a single non-phi value, if
10950 // so, scan to see if the phi cycle is actually equal to that value.
10951 {
10952 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10953 // Scan for the first non-phi operand.
10954 while (InValNo != NumOperandVals &&
10955 isa<PHINode>(PN.getIncomingValue(InValNo)))
10956 ++InValNo;
10957
10958 if (InValNo != NumOperandVals) {
10959 Value *NonPhiInVal = PN.getOperand(InValNo);
10960
10961 // Scan the rest of the operands to see if there are any conflicts, if so
10962 // there is no need to recursively scan other phis.
10963 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10964 Value *OpVal = PN.getIncomingValue(InValNo);
10965 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10966 break;
10967 }
10968
10969 // If we scanned over all operands, then we have one unique value plus
10970 // phi values. Scan PHI nodes to see if they all merge in each other or
10971 // the value.
10972 if (InValNo == NumOperandVals) {
10973 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10974 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10975 return ReplaceInstUsesWith(PN, NonPhiInVal);
10976 }
10977 }
10978 }
Chris Lattner60921c92003-12-19 05:58:40 +000010979 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010980}
10981
Reid Spencer17212df2006-12-12 09:18:51 +000010982static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10983 Instruction *InsertPoint,
10984 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010985 unsigned PtrSize = DTy->getScalarSizeInBits();
10986 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010987 // We must cast correctly to the pointer type. Ensure that we
10988 // sign extend the integer value if it is smaller as this is
10989 // used for address computation.
10990 Instruction::CastOps opcode =
10991 (VTySize < PtrSize ? Instruction::SExt :
10992 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10993 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010994}
10995
Chris Lattnera1be5662002-05-02 17:06:02 +000010996
Chris Lattner7e708292002-06-25 16:13:24 +000010997Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010998 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010999 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011000 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011001 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011002 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011003
Chris Lattnere87597f2004-10-16 18:11:37 +000011004 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011005 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011006
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011007 bool HasZeroPointerIndex = false;
11008 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11009 HasZeroPointerIndex = C->isNullValue();
11010
11011 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011012 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011013
Chris Lattner28977af2004-04-05 01:30:19 +000011014 // Eliminate unneeded casts for indices.
11015 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011016
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011017 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011018 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11019 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011020 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011021 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011022 if (CI->getOpcode() == Instruction::ZExt ||
11023 CI->getOpcode() == Instruction::SExt) {
11024 const Type *SrcTy = CI->getOperand(0)->getType();
11025 // We can eliminate a cast from i32 to i64 iff the target
11026 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011027 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011028 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011029 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011030 }
11031 }
11032 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011033 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011034 // to what we need. If narrower, sign-extend it to what we need.
11035 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011036 // insert it. This explicit cast can make subsequent optimizations more
11037 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011038 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011039 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011040 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000011041 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011042 MadeChange = true;
11043 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011044 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11045 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011046 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011047 MadeChange = true;
11048 }
Eric Christophera66297a2009-07-25 02:45:27 +000011049 } else if (TD->getTypeSizeInBits(Op->getType())
11050 < TD->getPointerSizeInBits()) {
Dan Gohman4f833d42008-09-11 23:06:38 +000011051 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000011052 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011053 MadeChange = true;
11054 } else {
11055 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11056 GEP);
11057 *i = Op;
11058 MadeChange = true;
11059 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011060 }
Chris Lattner28977af2004-04-05 01:30:19 +000011061 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011062 }
Chris Lattner28977af2004-04-05 01:30:19 +000011063 if (MadeChange) return &GEP;
11064
Chris Lattner90ac28c2002-08-02 19:29:35 +000011065 // Combine Indices - If the source pointer to this getelementptr instruction
11066 // is a getelementptr instruction, combine the indices of the two
11067 // getelementptr instructions into a single instruction.
11068 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011069 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011070 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11071 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner72588fc2007-02-15 22:48:32 +000011072 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011073 if (!Src->isInBounds())
11074 BothInBounds = false;
11075 }
Chris Lattnerebd985c2004-03-25 22:59:29 +000011076
11077 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011078 // Note that if our source is a gep chain itself that we wait for that
11079 // chain to be resolved before we perform this transformation. This
11080 // avoids us creating a TON of code in some cases.
11081 //
11082 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11083 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11084 return 0; // Wait until our source is folded to completion.
11085
Chris Lattner72588fc2007-02-15 22:48:32 +000011086 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011087
11088 // Find out whether the last index in the source GEP is a sequential idx.
11089 bool EndsWithSequential = false;
11090 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11091 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011092 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011093
Chris Lattner90ac28c2002-08-02 19:29:35 +000011094 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011095 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011096 // Replace: gep (gep %P, long B), long A, ...
11097 // With: T = long A+B; gep %P, T, ...
11098 //
Chris Lattner620ce142004-05-07 22:09:22 +000011099 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011100 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011101 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011102 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011103 Sum = SO1;
11104 } else {
11105 // If they aren't the same type, convert both to an integer of the
11106 // target's pointer size.
11107 if (SO1->getType() != GO1->getType()) {
11108 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011109 SO1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011110 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011111 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011112 GO1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011113 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011114 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011115 unsigned PS = TD->getPointerSizeInBits();
11116 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011117 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011118 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011119
Duncan Sands514ab342007-11-01 20:53:16 +000011120 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011121 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011122 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011123 } else {
11124 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011125 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11126 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011127 }
11128 }
11129 }
Chris Lattner620ce142004-05-07 22:09:22 +000011130 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011131 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Andersond672ecb2009-07-03 00:17:18 +000011132 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011133 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011134 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011135 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011136 }
Chris Lattner28977af2004-04-05 01:30:19 +000011137 }
Chris Lattner620ce142004-05-07 22:09:22 +000011138
11139 // Recycle the GEP we already have if possible.
11140 if (SrcGEPOperands.size() == 2) {
11141 GEP.setOperand(0, SrcGEPOperands[0]);
11142 GEP.setOperand(1, Sum);
11143 return &GEP;
11144 } else {
11145 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11146 SrcGEPOperands.end()-1);
11147 Indices.push_back(Sum);
11148 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11149 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011150 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011151 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011152 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011153 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011154 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11155 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011156 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11157 }
11158
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011159 if (!Indices.empty()) {
11160 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11161 Indices.begin(),
11162 Indices.end(),
11163 GEP.getName());
11164 if (BothInBounds)
11165 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11166 return NewGEP;
11167 }
Chris Lattner9b761232002-08-17 22:21:59 +000011168
Chris Lattner620ce142004-05-07 22:09:22 +000011169 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011170 // GEP of global variable. If all of the indices for this GEP are
11171 // constants, we can promote this to a constexpr instead of an instruction.
11172
11173 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011174 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011175 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11176 for (; I != E && isa<Constant>(*I); ++I)
11177 Indices.push_back(cast<Constant>(*I));
11178
11179 if (I == E) { // If they are all constants...
Owen Andersonbaf3c402009-07-29 18:55:55 +000011180 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011181 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011182
11183 // Replace all uses of the GEP with the new constexpr...
11184 return ReplaceInstUsesWith(GEP, CE);
11185 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011186 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011187 if (!isa<PointerType>(X->getType())) {
11188 // Not interesting. Source pointer must be a cast from pointer.
11189 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011190 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11191 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011192 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011193 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11194 // into : GEP i8* X, ...
11195 //
Chris Lattnereed48272005-09-13 00:40:14 +000011196 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011197 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11198 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011199 if (const ArrayType *CATy =
11200 dyn_cast<ArrayType>(CPTy->getElementType())) {
11201 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11202 if (CATy->getElementType() == XTy->getElementType()) {
11203 // -> GEP i8* X, ...
11204 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011205 GetElementPtrInst *NewGEP =
11206 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11207 GEP.getName());
11208 if (cast<GEPOperator>(&GEP)->isInBounds())
11209 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11210 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011211 } else if (const ArrayType *XATy =
11212 dyn_cast<ArrayType>(XTy->getElementType())) {
11213 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011214 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011215 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011216 // At this point, we know that the cast source type is a pointer
11217 // to an array of the same type as the destination pointer
11218 // array. Because the array type is never stepped over (there
11219 // is a leading zero) we can fold the cast into this GEP.
11220 GEP.setOperand(0, X);
11221 return &GEP;
11222 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011223 }
11224 }
Chris Lattnereed48272005-09-13 00:40:14 +000011225 } else if (GEP.getNumOperands() == 2) {
11226 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011227 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11228 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011229 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11230 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011231 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011232 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11233 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011234 Value *Idx[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011235 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011236 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011237 GetElementPtrInst *NewGEP =
11238 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11239 if (cast<GEPOperator>(&GEP)->isInBounds())
11240 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11241 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011242 // V and GEP are both pointer types --> BitCast
11243 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011244 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011245
11246 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011247 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011248 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011249 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011250
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011251 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011252 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011253 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011254
11255 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11256 // allow either a mul, shift, or constant here.
11257 Value *NewIdx = 0;
11258 ConstantInt *Scale = 0;
11259 if (ArrayEltSize == 1) {
11260 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011261 Scale =
Owen Andersoneed707b2009-07-24 23:12:02 +000011262 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011263 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011264 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011265 Scale = CI;
11266 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11267 if (Inst->getOpcode() == Instruction::Shl &&
11268 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011269 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11270 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011271 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011272 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011273 NewIdx = Inst->getOperand(0);
11274 } else if (Inst->getOpcode() == Instruction::Mul &&
11275 isa<ConstantInt>(Inst->getOperand(1))) {
11276 Scale = cast<ConstantInt>(Inst->getOperand(1));
11277 NewIdx = Inst->getOperand(0);
11278 }
11279 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011280
Chris Lattner7835cdd2005-09-13 18:36:04 +000011281 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011282 // out, perform the transformation. Note, we don't know whether Scale is
11283 // signed or not. We'll use unsigned version of division/modulo
11284 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011285 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011286 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011287 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011288 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011289 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011290 Constant *C =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011291 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011292 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011293 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011294 NewIdx = InsertNewInstBefore(Sc, GEP);
11295 }
11296
11297 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011298 Value *Idx[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011299 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011300 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011301 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011302 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011303 if (cast<GEPOperator>(&GEP)->isInBounds())
11304 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011305 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11306 // The NewGEP must be pointer typed, so must the old one -> BitCast
11307 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011308 }
11309 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011310 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011311 }
Chris Lattner58407792009-01-09 04:53:57 +000011312
Chris Lattner46cd5a12009-01-09 05:44:56 +000011313 /// See if we can simplify:
11314 /// X = bitcast A to B*
11315 /// Y = gep X, <...constant indices...>
11316 /// into a gep of the original struct. This is important for SROA and alias
11317 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011318 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011319 if (TD &&
11320 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011321 // Determine how much the GEP moves the pointer. We are guaranteed to get
11322 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011323 ConstantInt *OffsetV =
11324 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011325 int64_t Offset = OffsetV->getSExtValue();
11326
11327 // If this GEP instruction doesn't move the pointer, just replace the GEP
11328 // with a bitcast of the real input to the dest type.
11329 if (Offset == 0) {
11330 // If the bitcast is of an allocation, and the allocation will be
11331 // converted to match the type of the cast, don't touch this.
11332 if (isa<AllocationInst>(BCI->getOperand(0))) {
11333 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11334 if (Instruction *I = visitBitCast(*BCI)) {
11335 if (I != BCI) {
11336 I->takeName(BCI);
11337 BCI->getParent()->getInstList().insert(BCI, I);
11338 ReplaceInstUsesWith(*BCI, I);
11339 }
11340 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011341 }
Chris Lattner58407792009-01-09 04:53:57 +000011342 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011343 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011344 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011345
11346 // Otherwise, if the offset is non-zero, we need to find out if there is a
11347 // field at Offset in 'A's type. If so, we can pull the cast through the
11348 // GEP.
11349 SmallVector<Value*, 8> NewIndices;
11350 const Type *InTy =
11351 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011352 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011353 Instruction *NGEP =
11354 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11355 NewIndices.end());
11356 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011357 if (cast<GEPOperator>(&GEP)->isInBounds())
11358 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011359 InsertNewInstBefore(NGEP, GEP);
11360 NGEP->takeName(&GEP);
11361 return new BitCastInst(NGEP, GEP.getType());
11362 }
Chris Lattner58407792009-01-09 04:53:57 +000011363 }
11364 }
11365
Chris Lattner8a2a3112001-12-14 16:52:21 +000011366 return 0;
11367}
11368
Chris Lattner0864acf2002-11-04 16:18:53 +000011369Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11370 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011371 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011372 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11373 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011374 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011375 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011376
11377 // Create and insert the replacement instruction...
11378 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011379 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011380 else {
11381 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011382 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011383 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011384
11385 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011386
Chris Lattner0864acf2002-11-04 16:18:53 +000011387 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011388 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011389 //
11390 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011391 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011392
11393 // Now that I is pointing to the first non-allocation-inst in the block,
11394 // insert our getelementptr instruction...
11395 //
Owen Andersona7235ea2009-07-31 20:28:14 +000011396 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011397 Value *Idx[2];
11398 Idx[0] = NullIdx;
11399 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011400 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11401 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011402 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011403
11404 // Now make everything use the getelementptr instead of the original
11405 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011406 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011407 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011408 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011409 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011410 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011411
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011412 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011413 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011414 // Note that we only do this for alloca's, because malloc should allocate
11415 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011416 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011417 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011418
11419 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11420 if (AI.getAlignment() == 0)
11421 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11422 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011423
Chris Lattner0864acf2002-11-04 16:18:53 +000011424 return 0;
11425}
11426
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011427Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11428 Value *Op = FI.getOperand(0);
11429
Chris Lattner17be6352004-10-18 02:59:09 +000011430 // free undef -> unreachable.
11431 if (isa<UndefValue>(Op)) {
11432 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011433 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011434 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011435 return EraseInstFromFunction(FI);
11436 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011437
Chris Lattner6160e852004-02-28 04:57:37 +000011438 // If we have 'free null' delete the instruction. This can happen in stl code
11439 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011440 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011441 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011442
11443 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11444 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11445 FI.setOperand(0, CI->getOperand(0));
11446 return &FI;
11447 }
11448
11449 // Change free (gep X, 0,0,0,0) into free(X)
11450 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11451 if (GEPI->hasAllZeroIndices()) {
11452 AddToWorkList(GEPI);
11453 FI.setOperand(0, GEPI->getOperand(0));
11454 return &FI;
11455 }
11456 }
11457
11458 // Change free(malloc) into nothing, if the malloc has a single use.
11459 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11460 if (MI->hasOneUse()) {
11461 EraseInstFromFunction(FI);
11462 return EraseInstFromFunction(*MI);
11463 }
Chris Lattner6160e852004-02-28 04:57:37 +000011464
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011465 return 0;
11466}
11467
11468
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011469/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011470static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011471 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011472 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011473 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011474 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011475
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011476 if (TD) {
11477 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11478 // Instead of loading constant c string, use corresponding integer value
11479 // directly if string length is small enough.
11480 std::string Str;
11481 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11482 unsigned len = Str.length();
11483 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11484 unsigned numBits = Ty->getPrimitiveSizeInBits();
11485 // Replace LI with immediate integer store.
11486 if ((numBits >> 3) == len + 1) {
11487 APInt StrVal(numBits, 0);
11488 APInt SingleChar(numBits, 0);
11489 if (TD->isLittleEndian()) {
11490 for (signed i = len-1; i >= 0; i--) {
11491 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11492 StrVal = (StrVal << 8) | SingleChar;
11493 }
11494 } else {
11495 for (unsigned i = 0; i < len; i++) {
11496 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11497 StrVal = (StrVal << 8) | SingleChar;
11498 }
11499 // Append NULL at the end.
11500 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011501 StrVal = (StrVal << 8) | SingleChar;
11502 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011503 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011504 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011505 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011506 }
11507 }
11508 }
11509
Mon P Wang6753f952009-02-07 22:19:29 +000011510 const PointerType *DestTy = cast<PointerType>(CI->getType());
11511 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011512 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011513
11514 // If the address spaces don't match, don't eliminate the cast.
11515 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11516 return 0;
11517
Chris Lattnerb89e0712004-07-13 01:49:43 +000011518 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011519
Reid Spencer42230162007-01-22 05:51:25 +000011520 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011521 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011522 // If the source is an array, the code below will not succeed. Check to
11523 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11524 // constants.
11525 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11526 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11527 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011528 Value *Idxs[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011529 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
Owen Andersonbaf3c402009-07-29 18:55:55 +000011530 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011531 SrcTy = cast<PointerType>(CastOp->getType());
11532 SrcPTy = SrcTy->getElementType();
11533 }
11534
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011535 if (IC.getTargetData() &&
11536 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011537 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011538 // Do not allow turning this into a load of an integer, which is then
11539 // casted to a pointer, this pessimizes pointer analysis a lot.
11540 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011541 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11542 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011543
Chris Lattnerf9527852005-01-31 04:50:46 +000011544 // Okay, we are casting from one integer or pointer type to another of
11545 // the same size. Instead of casting the pointer before the load, cast
11546 // the result of the loaded value.
11547 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11548 CI->getName(),
11549 LI.isVolatile()),LI);
11550 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011551 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011552 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011553 }
11554 }
11555 return 0;
11556}
11557
Chris Lattner833b8a42003-06-26 05:06:25 +000011558Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11559 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011560
Dan Gohman9941f742007-07-20 16:34:21 +000011561 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011562 if (TD) {
11563 unsigned KnownAlign =
11564 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11565 if (KnownAlign >
11566 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11567 LI.getAlignment()))
11568 LI.setAlignment(KnownAlign);
11569 }
Dan Gohman9941f742007-07-20 16:34:21 +000011570
Chris Lattner37366c12005-05-01 04:24:53 +000011571 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011572 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011573 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011574 return Res;
11575
11576 // None of the following transforms are legal for volatile loads.
11577 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011578
Dan Gohman2276a7b2008-10-15 23:19:35 +000011579 // Do really simple store-to-load forwarding and load CSE, to catch cases
11580 // where there are several consequtive memory accesses to the same location,
11581 // separated by a few arithmetic operations.
11582 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011583 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11584 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011585
Christopher Lambb15147e2007-12-29 07:56:53 +000011586 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11587 const Value *GEPI0 = GEPI->getOperand(0);
11588 // TODO: Consider a target hook for valid address spaces for this xform.
11589 if (isa<ConstantPointerNull>(GEPI0) &&
11590 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011591 // Insert a new store to null instruction before the load to indicate
11592 // that this code is not reachable. We do this instead of inserting
11593 // an unreachable instruction directly because we cannot modify the
11594 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011595 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011596 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011597 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011598 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011599 }
Chris Lattner37366c12005-05-01 04:24:53 +000011600
Chris Lattnere87597f2004-10-16 18:11:37 +000011601 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011602 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011603 // TODO: Consider a target hook for valid address spaces for this xform.
11604 if (isa<UndefValue>(C) || (C->isNullValue() &&
11605 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011606 // Insert a new store to null instruction before the load to indicate that
11607 // this code is not reachable. We do this instead of inserting an
11608 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011609 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011610 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011611 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011612 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011613
Chris Lattnere87597f2004-10-16 18:11:37 +000011614 // Instcombine load (constant global) into the value loaded.
11615 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011616 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011617 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011618
Chris Lattnere87597f2004-10-16 18:11:37 +000011619 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011621 if (CE->getOpcode() == Instruction::GetElementPtr) {
11622 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011623 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011624 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011625 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011626 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011627 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011628 if (CE->getOperand(0)->isNullValue()) {
11629 // Insert a new store to null instruction before the load to indicate
11630 // that this code is not reachable. We do this instead of inserting
11631 // an unreachable instruction directly because we cannot modify the
11632 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011633 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011634 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011635 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011636 }
11637
Reid Spencer3da59db2006-11-27 01:05:10 +000011638 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011639 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011640 return Res;
11641 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011642 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011643 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011644
11645 // If this load comes from anywhere in a constant global, and if the global
11646 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011647 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011648 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011649 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011650 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011651 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011652 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011653 }
11654 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011655
Chris Lattner37366c12005-05-01 04:24:53 +000011656 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011657 // Change select and PHI nodes to select values instead of addresses: this
11658 // helps alias analysis out a lot, allows many others simplifications, and
11659 // exposes redundancy in the code.
11660 //
11661 // Note that we cannot do the transformation unless we know that the
11662 // introduced loads cannot trap! Something like this is valid as long as
11663 // the condition is always false: load (select bool %C, int* null, int* %G),
11664 // but it would not be valid if we transformed it to load from null
11665 // unconditionally.
11666 //
11667 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11668 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011669 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11670 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011671 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011672 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011673 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011674 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011675 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011676 }
11677
Chris Lattner684fe212004-09-23 15:46:00 +000011678 // load (select (cond, null, P)) -> load P
11679 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11680 if (C->isNullValue()) {
11681 LI.setOperand(0, SI->getOperand(2));
11682 return &LI;
11683 }
11684
11685 // load (select (cond, P, null)) -> load P
11686 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11687 if (C->isNullValue()) {
11688 LI.setOperand(0, SI->getOperand(1));
11689 return &LI;
11690 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011691 }
11692 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011693 return 0;
11694}
11695
Reid Spencer55af2b52007-01-19 21:20:31 +000011696/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011697/// when possible. This makes it generally easy to do alias analysis and/or
11698/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011699static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11700 User *CI = cast<User>(SI.getOperand(1));
11701 Value *CastOp = CI->getOperand(0);
11702
11703 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011704 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11705 if (SrcTy == 0) return 0;
11706
11707 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011708
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011709 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11710 return 0;
11711
Chris Lattner3914f722009-01-24 01:00:13 +000011712 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11713 /// to its first element. This allows us to handle things like:
11714 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11715 /// on 32-bit hosts.
11716 SmallVector<Value*, 4> NewGEPIndices;
11717
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011718 // If the source is an array, the code below will not succeed. Check to
11719 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11720 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011721 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11722 // Index through pointer.
Owen Andersona7235ea2009-07-31 20:28:14 +000011723 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011724 NewGEPIndices.push_back(Zero);
11725
11726 while (1) {
11727 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011728 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011729 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011730 NewGEPIndices.push_back(Zero);
11731 SrcPTy = STy->getElementType(0);
11732 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11733 NewGEPIndices.push_back(Zero);
11734 SrcPTy = ATy->getElementType();
11735 } else {
11736 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011737 }
Chris Lattner3914f722009-01-24 01:00:13 +000011738 }
11739
Owen Andersondebcb012009-07-29 22:17:13 +000011740 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011741 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011742
11743 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11744 return 0;
11745
Chris Lattner71759c42009-01-16 20:12:52 +000011746 // If the pointers point into different address spaces or if they point to
11747 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011748 if (!IC.getTargetData() ||
11749 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011750 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011751 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11752 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011753 return 0;
11754
11755 // Okay, we are casting from one integer or pointer type to another of
11756 // the same size. Instead of casting the pointer before
11757 // the store, cast the value to be stored.
11758 Value *NewCast;
11759 Value *SIOp0 = SI.getOperand(0);
11760 Instruction::CastOps opcode = Instruction::BitCast;
11761 const Type* CastSrcTy = SIOp0->getType();
11762 const Type* CastDstTy = SrcPTy;
11763 if (isa<PointerType>(CastDstTy)) {
11764 if (CastSrcTy->isInteger())
11765 opcode = Instruction::IntToPtr;
11766 } else if (isa<IntegerType>(CastDstTy)) {
11767 if (isa<PointerType>(SIOp0->getType()))
11768 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011769 }
Chris Lattner3914f722009-01-24 01:00:13 +000011770
11771 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11772 // emit a GEP to index into its first field.
11773 if (!NewGEPIndices.empty()) {
11774 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011775 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011776 NewGEPIndices.size());
11777 else
11778 CastOp = IC.InsertNewInstBefore(
11779 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11780 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011781 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011782 }
11783
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011784 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011785 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011786 else
11787 NewCast = IC.InsertNewInstBefore(
11788 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11789 SI);
11790 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011791}
11792
Chris Lattner4aebaee2008-11-27 08:56:30 +000011793/// equivalentAddressValues - Test if A and B will obviously have the same
11794/// value. This includes recognizing that %t0 and %t1 will have the same
11795/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011796/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011797/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011798/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011799/// %t2 = load i32* %t1
11800///
11801static bool equivalentAddressValues(Value *A, Value *B) {
11802 // Test if the values are trivially equivalent.
11803 if (A == B) return true;
11804
11805 // Test if the values come form identical arithmetic instructions.
11806 if (isa<BinaryOperator>(A) ||
11807 isa<CastInst>(A) ||
11808 isa<PHINode>(A) ||
11809 isa<GetElementPtrInst>(A))
11810 if (Instruction *BI = dyn_cast<Instruction>(B))
11811 if (cast<Instruction>(A)->isIdenticalTo(BI))
11812 return true;
11813
11814 // Otherwise they may not be equivalent.
11815 return false;
11816}
11817
Dale Johannesen4945c652009-03-03 21:26:39 +000011818// If this instruction has two uses, one of which is a llvm.dbg.declare,
11819// return the llvm.dbg.declare.
11820DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11821 if (!V->hasNUses(2))
11822 return 0;
11823 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11824 UI != E; ++UI) {
11825 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11826 return DI;
11827 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11828 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11829 return DI;
11830 }
11831 }
11832 return 0;
11833}
11834
Chris Lattner2f503e62005-01-31 05:36:43 +000011835Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11836 Value *Val = SI.getOperand(0);
11837 Value *Ptr = SI.getOperand(1);
11838
11839 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011840 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011841 ++NumCombined;
11842 return 0;
11843 }
Chris Lattner836692d2007-01-15 06:51:56 +000011844
11845 // If the RHS is an alloca with a single use, zapify the store, making the
11846 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011847 // If the RHS is an alloca with a two uses, the other one being a
11848 // llvm.dbg.declare, zapify the store and the declare, making the
11849 // alloca dead. We must do this to prevent declare's from affecting
11850 // codegen.
11851 if (!SI.isVolatile()) {
11852 if (Ptr->hasOneUse()) {
11853 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011854 EraseInstFromFunction(SI);
11855 ++NumCombined;
11856 return 0;
11857 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011858 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11859 if (isa<AllocaInst>(GEP->getOperand(0))) {
11860 if (GEP->getOperand(0)->hasOneUse()) {
11861 EraseInstFromFunction(SI);
11862 ++NumCombined;
11863 return 0;
11864 }
11865 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11866 EraseInstFromFunction(*DI);
11867 EraseInstFromFunction(SI);
11868 ++NumCombined;
11869 return 0;
11870 }
11871 }
11872 }
11873 }
11874 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11875 EraseInstFromFunction(*DI);
11876 EraseInstFromFunction(SI);
11877 ++NumCombined;
11878 return 0;
11879 }
Chris Lattner836692d2007-01-15 06:51:56 +000011880 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011881
Dan Gohman9941f742007-07-20 16:34:21 +000011882 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011883 if (TD) {
11884 unsigned KnownAlign =
11885 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11886 if (KnownAlign >
11887 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11888 SI.getAlignment()))
11889 SI.setAlignment(KnownAlign);
11890 }
Dan Gohman9941f742007-07-20 16:34:21 +000011891
Dale Johannesenacb51a32009-03-03 01:43:03 +000011892 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011893 // stores to the same location, separated by a few arithmetic operations. This
11894 // situation often occurs with bitfield accesses.
11895 BasicBlock::iterator BBI = &SI;
11896 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11897 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011898 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011899 // Don't count debug info directives, lest they affect codegen,
11900 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11901 // It is necessary for correctness to skip those that feed into a
11902 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011903 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011904 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011905 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011906 continue;
11907 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011908
11909 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11910 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011911 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11912 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011913 ++NumDeadStore;
11914 ++BBI;
11915 EraseInstFromFunction(*PrevSI);
11916 continue;
11917 }
11918 break;
11919 }
11920
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011921 // If this is a load, we have to stop. However, if the loaded value is from
11922 // the pointer we're loading and is producing the pointer we're storing,
11923 // then *this* store is dead (X = load P; store X -> P).
11924 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011925 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11926 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011927 EraseInstFromFunction(SI);
11928 ++NumCombined;
11929 return 0;
11930 }
11931 // Otherwise, this is a load from some other location. Stores before it
11932 // may not be dead.
11933 break;
11934 }
11935
Chris Lattner9ca96412006-02-08 03:25:32 +000011936 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011937 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011938 break;
11939 }
11940
11941
11942 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011943
11944 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011945 if (isa<ConstantPointerNull>(Ptr) &&
11946 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011947 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011948 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011949 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011950 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011951 ++NumCombined;
11952 }
11953 return 0; // Do not modify these!
11954 }
11955
11956 // store undef, Ptr -> noop
11957 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011958 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011959 ++NumCombined;
11960 return 0;
11961 }
11962
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011963 // If the pointer destination is a cast, see if we can fold the cast into the
11964 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011965 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011966 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11967 return Res;
11968 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011969 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011970 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11971 return Res;
11972
Chris Lattner408902b2005-09-12 23:23:25 +000011973
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011974 // If this store is the last instruction in the basic block (possibly
11975 // excepting debug info instructions and the pointer bitcasts that feed
11976 // into them), and if the block ends with an unconditional branch, try
11977 // to move it to the successor block.
11978 BBI = &SI;
11979 do {
11980 ++BBI;
11981 } while (isa<DbgInfoIntrinsic>(BBI) ||
11982 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011983 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011984 if (BI->isUnconditional())
11985 if (SimplifyStoreAtEndOfBlock(SI))
11986 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011987
Chris Lattner2f503e62005-01-31 05:36:43 +000011988 return 0;
11989}
11990
Chris Lattner3284d1f2007-04-15 00:07:55 +000011991/// SimplifyStoreAtEndOfBlock - Turn things like:
11992/// if () { *P = v1; } else { *P = v2 }
11993/// into a phi node with a store in the successor.
11994///
Chris Lattner31755a02007-04-15 01:02:18 +000011995/// Simplify things like:
11996/// *P = v1; if () { *P = v2; }
11997/// into a phi node with a store in the successor.
11998///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011999bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12000 BasicBlock *StoreBB = SI.getParent();
12001
12002 // Check to see if the successor block has exactly two incoming edges. If
12003 // so, see if the other predecessor contains a store to the same location.
12004 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012005 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012006
12007 // Determine whether Dest has exactly two predecessors and, if so, compute
12008 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012009 pred_iterator PI = pred_begin(DestBB);
12010 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012011 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012012 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012013 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012014 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012015 return false;
12016
12017 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012018 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012019 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012020 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 }
Chris Lattner31755a02007-04-15 01:02:18 +000012022 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012023 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012024
12025 // Bail out if all the relevant blocks aren't distinct (this can happen,
12026 // for example, if SI is in an infinite loop)
12027 if (StoreBB == DestBB || OtherBB == DestBB)
12028 return false;
12029
Chris Lattner31755a02007-04-15 01:02:18 +000012030 // Verify that the other block ends in a branch and is not otherwise empty.
12031 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012032 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012033 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012034 return false;
12035
Chris Lattner31755a02007-04-15 01:02:18 +000012036 // If the other block ends in an unconditional branch, check for the 'if then
12037 // else' case. there is an instruction before the branch.
12038 StoreInst *OtherStore = 0;
12039 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012040 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012041 // Skip over debugging info.
12042 while (isa<DbgInfoIntrinsic>(BBI) ||
12043 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12044 if (BBI==OtherBB->begin())
12045 return false;
12046 --BBI;
12047 }
12048 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012049 OtherStore = dyn_cast<StoreInst>(BBI);
12050 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12051 return false;
12052 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012053 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012054 // destinations is StoreBB, then we have the if/then case.
12055 if (OtherBr->getSuccessor(0) != StoreBB &&
12056 OtherBr->getSuccessor(1) != StoreBB)
12057 return false;
12058
12059 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012060 // if/then triangle. See if there is a store to the same ptr as SI that
12061 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012062 for (;; --BBI) {
12063 // Check to see if we find the matching store.
12064 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12065 if (OtherStore->getOperand(1) != SI.getOperand(1))
12066 return false;
12067 break;
12068 }
Eli Friedman6903a242008-06-13 22:02:12 +000012069 // If we find something that may be using or overwriting the stored
12070 // value, or if we run out of instructions, we can't do the xform.
12071 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012072 BBI == OtherBB->begin())
12073 return false;
12074 }
12075
12076 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012077 // make sure nothing reads or overwrites the stored value in
12078 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012079 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12080 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012081 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012082 return false;
12083 }
12084 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012085
Chris Lattner31755a02007-04-15 01:02:18 +000012086 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012087 Value *MergedVal = OtherStore->getOperand(0);
12088 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012089 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012090 PN->reserveOperandSpace(2);
12091 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012092 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12093 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012094 }
12095
12096 // Advance to a place where it is safe to insert the new store and
12097 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012098 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012099 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12100 OtherStore->isVolatile()), *BBI);
12101
12102 // Nuke the old stores.
12103 EraseInstFromFunction(SI);
12104 EraseInstFromFunction(*OtherStore);
12105 ++NumCombined;
12106 return true;
12107}
12108
Chris Lattner2f503e62005-01-31 05:36:43 +000012109
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012110Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12111 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012112 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012113 BasicBlock *TrueDest;
12114 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012115 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012116 !isa<Constant>(X)) {
12117 // Swap Destinations and condition...
12118 BI.setCondition(X);
12119 BI.setSuccessor(0, FalseDest);
12120 BI.setSuccessor(1, TrueDest);
12121 return &BI;
12122 }
12123
Reid Spencere4d87aa2006-12-23 06:05:41 +000012124 // Cannonicalize fcmp_one -> fcmp_oeq
12125 FCmpInst::Predicate FPred; Value *Y;
12126 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012127 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012128 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12129 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12130 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012131 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012132 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012133 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012134 // Swap Destinations and condition...
12135 BI.setCondition(NewSCC);
12136 BI.setSuccessor(0, FalseDest);
12137 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012138 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012139 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012140 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012141 return &BI;
12142 }
12143
12144 // Cannonicalize icmp_ne -> icmp_eq
12145 ICmpInst::Predicate IPred;
12146 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012147 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012148 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12149 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12150 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12151 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012152 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012153 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012154 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012155 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012156 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012157 BI.setSuccessor(0, FalseDest);
12158 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012159 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012160 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012161 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012162 return &BI;
12163 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012164
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012165 return 0;
12166}
Chris Lattner0864acf2002-11-04 16:18:53 +000012167
Chris Lattner46238a62004-07-03 00:26:11 +000012168Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12169 Value *Cond = SI.getCondition();
12170 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12171 if (I->getOpcode() == Instruction::Add)
12172 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12173 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12174 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012175 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012176 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012177 AddRHS));
12178 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012179 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012180 return &SI;
12181 }
12182 }
12183 return 0;
12184}
12185
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012186Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012187 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012188
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012189 if (!EV.hasIndices())
12190 return ReplaceInstUsesWith(EV, Agg);
12191
12192 if (Constant *C = dyn_cast<Constant>(Agg)) {
12193 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012194 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012195
12196 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012197 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012198
12199 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12200 // Extract the element indexed by the first index out of the constant
12201 Value *V = C->getOperand(*EV.idx_begin());
12202 if (EV.getNumIndices() > 1)
12203 // Extract the remaining indices out of the constant indexed by the
12204 // first index
12205 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12206 else
12207 return ReplaceInstUsesWith(EV, V);
12208 }
12209 return 0; // Can't handle other constants
12210 }
12211 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12212 // We're extracting from an insertvalue instruction, compare the indices
12213 const unsigned *exti, *exte, *insi, *inse;
12214 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12215 exte = EV.idx_end(), inse = IV->idx_end();
12216 exti != exte && insi != inse;
12217 ++exti, ++insi) {
12218 if (*insi != *exti)
12219 // The insert and extract both reference distinctly different elements.
12220 // This means the extract is not influenced by the insert, and we can
12221 // replace the aggregate operand of the extract with the aggregate
12222 // operand of the insert. i.e., replace
12223 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12224 // %E = extractvalue { i32, { i32 } } %I, 0
12225 // with
12226 // %E = extractvalue { i32, { i32 } } %A, 0
12227 return ExtractValueInst::Create(IV->getAggregateOperand(),
12228 EV.idx_begin(), EV.idx_end());
12229 }
12230 if (exti == exte && insi == inse)
12231 // Both iterators are at the end: Index lists are identical. Replace
12232 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12233 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12234 // with "i32 42"
12235 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12236 if (exti == exte) {
12237 // The extract list is a prefix of the insert list. i.e. replace
12238 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12239 // %E = extractvalue { i32, { i32 } } %I, 1
12240 // with
12241 // %X = extractvalue { i32, { i32 } } %A, 1
12242 // %E = insertvalue { i32 } %X, i32 42, 0
12243 // by switching the order of the insert and extract (though the
12244 // insertvalue should be left in, since it may have other uses).
12245 Value *NewEV = InsertNewInstBefore(
12246 ExtractValueInst::Create(IV->getAggregateOperand(),
12247 EV.idx_begin(), EV.idx_end()),
12248 EV);
12249 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12250 insi, inse);
12251 }
12252 if (insi == inse)
12253 // The insert list is a prefix of the extract list
12254 // We can simply remove the common indices from the extract and make it
12255 // operate on the inserted value instead of the insertvalue result.
12256 // i.e., replace
12257 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12258 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12259 // with
12260 // %E extractvalue { i32 } { i32 42 }, 0
12261 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12262 exti, exte);
12263 }
12264 // Can't simplify extracts from other values. Note that nested extracts are
12265 // already simplified implicitely by the above (extract ( extract (insert) )
12266 // will be translated into extract ( insert ( extract ) ) first and then just
12267 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012268 return 0;
12269}
12270
Chris Lattner220b0cf2006-03-05 00:22:33 +000012271/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12272/// is to leave as a vector operation.
12273static bool CheapToScalarize(Value *V, bool isConstant) {
12274 if (isa<ConstantAggregateZero>(V))
12275 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012276 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012277 if (isConstant) return true;
12278 // If all elts are the same, we can extract.
12279 Constant *Op0 = C->getOperand(0);
12280 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12281 if (C->getOperand(i) != Op0)
12282 return false;
12283 return true;
12284 }
12285 Instruction *I = dyn_cast<Instruction>(V);
12286 if (!I) return false;
12287
12288 // Insert element gets simplified to the inserted element or is deleted if
12289 // this is constant idx extract element and its a constant idx insertelt.
12290 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12291 isa<ConstantInt>(I->getOperand(2)))
12292 return true;
12293 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12294 return true;
12295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12296 if (BO->hasOneUse() &&
12297 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12298 CheapToScalarize(BO->getOperand(1), isConstant)))
12299 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012300 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12301 if (CI->hasOneUse() &&
12302 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12303 CheapToScalarize(CI->getOperand(1), isConstant)))
12304 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012305
12306 return false;
12307}
12308
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012309/// Read and decode a shufflevector mask.
12310///
12311/// It turns undef elements into values that are larger than the number of
12312/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012313static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12314 unsigned NElts = SVI->getType()->getNumElements();
12315 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12316 return std::vector<unsigned>(NElts, 0);
12317 if (isa<UndefValue>(SVI->getOperand(2)))
12318 return std::vector<unsigned>(NElts, 2*NElts);
12319
12320 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012321 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012322 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12323 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012324 Result.push_back(NElts*2); // undef -> 8
12325 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012326 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012327 return Result;
12328}
12329
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012330/// FindScalarElement - Given a vector and an element number, see if the scalar
12331/// value is already around as a register, for example if it were inserted then
12332/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012333static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012334 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012335 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12336 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012337 unsigned Width = PTy->getNumElements();
12338 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012339 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012340
12341 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012342 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012343 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012344 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012345 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012346 return CP->getOperand(EltNo);
12347 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12348 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012349 if (!isa<ConstantInt>(III->getOperand(2)))
12350 return 0;
12351 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012352
12353 // If this is an insert to the element we are looking for, return the
12354 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012355 if (EltNo == IIElt)
12356 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012357
12358 // Otherwise, the insertelement doesn't modify the value, recurse on its
12359 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012360 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012361 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012362 unsigned LHSWidth =
12363 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012364 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012365 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012366 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012367 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012368 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012369 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012370 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012371 }
12372
12373 // Otherwise, we don't know.
12374 return 0;
12375}
12376
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012377Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012378 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012379 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012380 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012381
Dan Gohman07a96762007-07-16 14:29:03 +000012382 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012383 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012384 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012385
Reid Spencer9d6565a2007-02-15 02:26:10 +000012386 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012387 // If vector val is constant with all elements the same, replace EI with
12388 // that element. When the elements are not identical, we cannot replace yet
12389 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012390 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012391 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012392 if (C->getOperand(i) != op0) {
12393 op0 = 0;
12394 break;
12395 }
12396 if (op0)
12397 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012398 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012399
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012400 // If extracting a specified index from the vector, see if we can recursively
12401 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012402 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012403 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012404 unsigned VectorWidth =
12405 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012406
12407 // If this is extracting an invalid index, turn this into undef, to avoid
12408 // crashing the code below.
12409 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012410 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012411
Chris Lattner867b99f2006-10-05 06:55:50 +000012412 // This instruction only demands the single element from the input vector.
12413 // If the input vector has a single use, simplify it based on this use
12414 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012415 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012416 APInt UndefElts(VectorWidth, 0);
12417 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012418 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012419 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012420 EI.setOperand(0, V);
12421 return &EI;
12422 }
12423 }
12424
Owen Andersond672ecb2009-07-03 00:17:18 +000012425 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012426 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012427
12428 // If the this extractelement is directly using a bitcast from a vector of
12429 // the same number of elements, see if we can find the source element from
12430 // it. In this case, we will end up needing to bitcast the scalars.
12431 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12432 if (const VectorType *VT =
12433 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12434 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012435 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12436 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012437 return new BitCastInst(Elt, EI.getType());
12438 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012439 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012440
Chris Lattner73fa49d2006-05-25 22:53:38 +000012441 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012442 if (I->hasOneUse()) {
12443 // Push extractelement into predecessor operation if legal and
12444 // profitable to do so
12445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012446 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12447 if (CheapToScalarize(BO, isConstantElt)) {
12448 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012449 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012450 EI.getName()+".lhs");
12451 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012452 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012453 EI.getName()+".rhs");
12454 InsertNewInstBefore(newEI0, EI);
12455 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012456 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012457 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012458 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012459 unsigned AS =
12460 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012461 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersondebcb012009-07-29 22:17:13 +000012462 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012463 GetElementPtrInst *GEP =
12464 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012465 cast<GEPOperator>(GEP)->setIsInBounds(true);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012466 InsertNewInstBefore(GEP, EI);
12467 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012468 }
12469 }
12470 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12471 // Extracting the inserted element?
12472 if (IE->getOperand(2) == EI.getOperand(1))
12473 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12474 // If the inserted and extracted elements are constants, they must not
12475 // be the same value, extract from the pre-inserted value instead.
12476 if (isa<Constant>(IE->getOperand(2)) &&
12477 isa<Constant>(EI.getOperand(1))) {
12478 AddUsesToWorkList(EI);
12479 EI.setOperand(0, IE->getOperand(0));
12480 return &EI;
12481 }
12482 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12483 // If this is extracting an element from a shufflevector, figure out where
12484 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012485 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12486 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012487 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012488 unsigned LHSWidth =
12489 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12490
12491 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012492 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012493 else if (SrcIdx < LHSWidth*2) {
12494 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012495 Src = SVI->getOperand(1);
12496 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012497 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012498 }
Eric Christophera3500da2009-07-25 02:28:41 +000012499 return ExtractElementInst::Create(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +000012500 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012501 }
12502 }
Eli Friedman2451a642009-07-18 23:06:53 +000012503 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012504 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012505 return 0;
12506}
12507
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012508/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12509/// elements from either LHS or RHS, return the shuffle mask and true.
12510/// Otherwise, return false.
12511static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012512 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012513 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012514 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12515 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012516 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012517
12518 if (isa<UndefValue>(V)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012519 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012520 return true;
12521 } else if (V == LHS) {
12522 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012523 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012524 return true;
12525 } else if (V == RHS) {
12526 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012527 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012528 return true;
12529 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12530 // If this is an insert of an extract from some other vector, include it.
12531 Value *VecOp = IEI->getOperand(0);
12532 Value *ScalarOp = IEI->getOperand(1);
12533 Value *IdxOp = IEI->getOperand(2);
12534
Chris Lattnerd929f062006-04-27 21:14:21 +000012535 if (!isa<ConstantInt>(IdxOp))
12536 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012537 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012538
12539 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12540 // Okay, we can handle this if the vector we are insertinting into is
12541 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012542 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012543 // If so, update the mask to reflect the inserted undef.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012544 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012545 return true;
12546 }
12547 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12548 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012549 EI->getOperand(0)->getType() == V->getType()) {
12550 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012551 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012552
12553 // This must be extracting from either LHS or RHS.
12554 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12555 // Okay, we can handle this if the vector we are insertinting into is
12556 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012557 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012558 // If so, update the mask to reflect the inserted value.
12559 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012560 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012561 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012562 } else {
12563 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012564 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012565 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012566
12567 }
12568 return true;
12569 }
12570 }
12571 }
12572 }
12573 }
12574 // TODO: Handle shufflevector here!
12575
12576 return false;
12577}
12578
12579/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12580/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12581/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012582static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012583 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012584 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012585 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012586 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012587 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012588
12589 if (isa<UndefValue>(V)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012590 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012591 return V;
12592 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012593 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012594 return V;
12595 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12596 // If this is an insert of an extract from some other vector, include it.
12597 Value *VecOp = IEI->getOperand(0);
12598 Value *ScalarOp = IEI->getOperand(1);
12599 Value *IdxOp = IEI->getOperand(2);
12600
12601 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12602 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12603 EI->getOperand(0)->getType() == V->getType()) {
12604 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012605 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12606 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012607
12608 // Either the extracted from or inserted into vector must be RHSVec,
12609 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012610 if (EI->getOperand(0) == RHS || RHS == 0) {
12611 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012612 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012613 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012614 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012615 return V;
12616 }
12617
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012618 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012619 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12620 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012621 // Everything but the extracted element is replaced with the RHS.
12622 for (unsigned i = 0; i != NumElts; ++i) {
12623 if (i != InsertedIdx)
Owen Andersoneed707b2009-07-24 23:12:02 +000012624 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012625 }
12626 return V;
12627 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012628
12629 // If this insertelement is a chain that comes from exactly these two
12630 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012631 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12632 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012633 return EI->getOperand(0);
12634
Chris Lattnerefb47352006-04-15 01:39:45 +000012635 }
12636 }
12637 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012638 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012639
12640 // Otherwise, can't do anything fancy. Return an identity vector.
12641 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012642 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012643 return V;
12644}
12645
12646Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12647 Value *VecOp = IE.getOperand(0);
12648 Value *ScalarOp = IE.getOperand(1);
12649 Value *IdxOp = IE.getOperand(2);
12650
Chris Lattner599ded12007-04-09 01:11:16 +000012651 // Inserting an undef or into an undefined place, remove this.
12652 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12653 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012654
Chris Lattnerefb47352006-04-15 01:39:45 +000012655 // If the inserted element was extracted from some other vector, and if the
12656 // indexes are constant, try to turn this into a shufflevector operation.
12657 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12658 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12659 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012660 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012661 unsigned ExtractedIdx =
12662 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012663 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012664
12665 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12666 return ReplaceInstUsesWith(IE, VecOp);
12667
12668 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012669 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012670
12671 // If we are extracting a value from a vector, then inserting it right
12672 // back into the same place, just use the input vector.
12673 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12674 return ReplaceInstUsesWith(IE, VecOp);
12675
12676 // We could theoretically do this for ANY input. However, doing so could
12677 // turn chains of insertelement instructions into a chain of shufflevector
12678 // instructions, and right now we do not merge shufflevectors. As such,
12679 // only do this in a situation where it is clear that there is benefit.
12680 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12681 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12682 // the values of VecOp, except then one read from EIOp0.
12683 // Build a new shuffle mask.
12684 std::vector<Constant*> Mask;
12685 if (isa<UndefValue>(VecOp))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012686 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012687 else {
12688 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneed707b2009-07-24 23:12:02 +000012689 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012690 NumVectorElts));
12691 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012692 Mask[InsertedIdx] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012693 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012694 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012695 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012696 }
12697
12698 // If this insertelement isn't used by some other insertelement, turn it
12699 // (and any insertelements it points to), into one big shuffle.
12700 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12701 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012702 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012703 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012704 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012705 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012706 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012707 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012708 }
12709 }
12710 }
12711
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012712 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12713 APInt UndefElts(VWidth, 0);
12714 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12715 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12716 return &IE;
12717
Chris Lattnerefb47352006-04-15 01:39:45 +000012718 return 0;
12719}
12720
12721
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012722Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12723 Value *LHS = SVI.getOperand(0);
12724 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012725 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012726
12727 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012728
Chris Lattner867b99f2006-10-05 06:55:50 +000012729 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012730 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012731 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012732
Dan Gohman488fbfc2008-09-09 18:11:14 +000012733 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012734
12735 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12736 return 0;
12737
Evan Cheng388df622009-02-03 10:05:09 +000012738 APInt UndefElts(VWidth, 0);
12739 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12740 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012741 LHS = SVI.getOperand(0);
12742 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012743 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012744 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012745
Chris Lattner863bcff2006-05-25 23:48:38 +000012746 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12747 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12748 if (LHS == RHS || isa<UndefValue>(LHS)) {
12749 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012750 // shuffle(undef,undef,mask) -> undef.
12751 return ReplaceInstUsesWith(SVI, LHS);
12752 }
12753
Chris Lattner863bcff2006-05-25 23:48:38 +000012754 // Remap any references to RHS to use LHS.
12755 std::vector<Constant*> Elts;
12756 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012757 if (Mask[i] >= 2*e)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012758 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012759 else {
12760 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012761 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012762 Mask[i] = 2*e; // Turn into undef.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012763 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012764 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012765 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneed707b2009-07-24 23:12:02 +000012766 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012767 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012768 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012769 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012770 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012771 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012772 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012773 LHS = SVI.getOperand(0);
12774 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012775 MadeChange = true;
12776 }
12777
Chris Lattner7b2e27922006-05-26 00:29:06 +000012778 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012779 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012780
Chris Lattner863bcff2006-05-25 23:48:38 +000012781 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12782 if (Mask[i] >= e*2) continue; // Ignore undef values.
12783 // Is this an identity shuffle of the LHS value?
12784 isLHSID &= (Mask[i] == i);
12785
12786 // Is this an identity shuffle of the RHS value?
12787 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012788 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012789
Chris Lattner863bcff2006-05-25 23:48:38 +000012790 // Eliminate identity shuffles.
12791 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12792 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012793
Chris Lattner7b2e27922006-05-26 00:29:06 +000012794 // If the LHS is a shufflevector itself, see if we can combine it with this
12795 // one without producing an unusual shuffle. Here we are really conservative:
12796 // we are absolutely afraid of producing a shuffle mask not in the input
12797 // program, because the code gen may not be smart enough to turn a merged
12798 // shuffle into two specific shuffles: it may produce worse code. As such,
12799 // we only merge two shuffles if the result is one of the two input shuffle
12800 // masks. In this case, merging the shuffles just removes one instruction,
12801 // which we know is safe. This is good for things like turning:
12802 // (splat(splat)) -> splat.
12803 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12804 if (isa<UndefValue>(RHS)) {
12805 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12806
12807 std::vector<unsigned> NewMask;
12808 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12809 if (Mask[i] >= 2*e)
12810 NewMask.push_back(2*e);
12811 else
12812 NewMask.push_back(LHSMask[Mask[i]]);
12813
12814 // If the result mask is equal to the src shuffle or this shuffle mask, do
12815 // the replacement.
12816 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012817 unsigned LHSInNElts =
12818 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012819 std::vector<Constant*> Elts;
12820 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012821 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012822 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012823 } else {
Owen Andersoneed707b2009-07-24 23:12:02 +000012824 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012825 }
12826 }
12827 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12828 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012829 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012830 }
12831 }
12832 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012833
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012834 return MadeChange ? &SVI : 0;
12835}
12836
12837
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012838
Chris Lattnerea1c4542004-12-08 23:43:58 +000012839
12840/// TryToSinkInstruction - Try to move the specified instruction from its
12841/// current block into the beginning of DestBlock, which can only happen if it's
12842/// safe to move the instruction past all of the instructions between it and the
12843/// end of its block.
12844static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12845 assert(I->hasOneUse() && "Invariants didn't hold!");
12846
Chris Lattner108e9022005-10-27 17:13:11 +000012847 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012848 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012849 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012850
Chris Lattnerea1c4542004-12-08 23:43:58 +000012851 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012852 if (isa<AllocaInst>(I) && I->getParent() ==
12853 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012854 return false;
12855
Chris Lattner96a52a62004-12-09 07:14:34 +000012856 // We can only sink load instructions if there is nothing between the load and
12857 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012858 if (I->mayReadFromMemory()) {
12859 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012860 Scan != E; ++Scan)
12861 if (Scan->mayWriteToMemory())
12862 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012863 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012864
Dan Gohman02dea8b2008-05-23 21:05:58 +000012865 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012866
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012867 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012868 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012869 ++NumSunkInst;
12870 return true;
12871}
12872
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012873
12874/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12875/// all reachable code to the worklist.
12876///
12877/// This has a couple of tricks to make the code faster and more powerful. In
12878/// particular, we constant fold and DCE instructions as we go, to avoid adding
12879/// them to the worklist (this significantly speeds up instcombine on code where
12880/// many instructions are dead or constant). Additionally, if we find a branch
12881/// whose condition is a known constant, we only visit the reachable successors.
12882///
12883static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012884 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012885 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012886 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012887 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012888 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012889
Chris Lattner2c7718a2007-03-23 19:17:18 +000012890 while (!Worklist.empty()) {
12891 BB = Worklist.back();
12892 Worklist.pop_back();
12893
12894 // We have now visited this block! If we've already been here, ignore it.
12895 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012896
12897 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012898 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12899 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012900
Chris Lattner2c7718a2007-03-23 19:17:18 +000012901 // DCE instruction if trivially dead.
12902 if (isInstructionTriviallyDead(Inst)) {
12903 ++NumDeadInst;
12904 DOUT << "IC: DCE: " << *Inst;
12905 Inst->eraseFromParent();
12906 continue;
12907 }
12908
12909 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012910 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012911 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12912 Inst->replaceAllUsesWith(C);
12913 ++NumConstProp;
12914 Inst->eraseFromParent();
12915 continue;
12916 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012917
Devang Patel7fe1dec2008-11-19 18:56:50 +000012918 // If there are two consecutive llvm.dbg.stoppoint calls then
12919 // it is likely that the optimizer deleted code in between these
12920 // two intrinsics.
12921 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12922 if (DBI_Next) {
12923 if (DBI_Prev
12924 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12925 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12926 IC.RemoveFromWorkList(DBI_Prev);
12927 DBI_Prev->eraseFromParent();
12928 }
12929 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012930 } else {
12931 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012932 }
12933
Chris Lattner2c7718a2007-03-23 19:17:18 +000012934 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012935 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012936
12937 // Recursively visit successors. If this is a branch or switch on a
12938 // constant, only visit the reachable successor.
12939 TerminatorInst *TI = BB->getTerminator();
12940 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12941 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12942 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012943 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012944 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012945 continue;
12946 }
12947 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12948 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12949 // See if this is an explicit destination.
12950 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12951 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012952 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012953 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012954 continue;
12955 }
12956
12957 // Otherwise it is the default destination.
12958 Worklist.push_back(SI->getSuccessor(0));
12959 continue;
12960 }
12961 }
12962
12963 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12964 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012965 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012966}
12967
Chris Lattnerec9c3582007-03-03 02:04:50 +000012968bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012969 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012970 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012971
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012972 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12973 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012974
Chris Lattnerb3d59702005-07-07 20:40:38 +000012975 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012976 // Do a depth-first traversal of the function, populate the worklist with
12977 // the reachable instructions. Ignore blocks that are not reachable. Keep
12978 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012979 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012980 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012981
Chris Lattnerb3d59702005-07-07 20:40:38 +000012982 // Do a quick scan over the function. If we find any blocks that are
12983 // unreachable, remove any instructions inside of them. This prevents
12984 // the instcombine code from having to deal with some bad special cases.
12985 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12986 if (!Visited.count(BB)) {
12987 Instruction *Term = BB->getTerminator();
12988 while (Term != BB->begin()) { // Remove instrs bottom-up
12989 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012990
Bill Wendlingb7427032006-11-26 09:46:52 +000012991 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012992 // A debug intrinsic shouldn't force another iteration if we weren't
12993 // going to do one without it.
12994 if (!isa<DbgInfoIntrinsic>(I)) {
12995 ++NumDeadInst;
12996 Changed = true;
12997 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012998 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012999 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013000 I->eraseFromParent();
13001 }
13002 }
13003 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013004
Chris Lattnerdbab3862007-03-02 21:28:56 +000013005 while (!Worklist.empty()) {
13006 Instruction *I = RemoveOneFromWorkList();
13007 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013008
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013009 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013010 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013011 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000013012 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013013 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000013014 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013015
Bill Wendlingb7427032006-11-26 09:46:52 +000013016 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013017
13018 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013019 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013020 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013021 continue;
13022 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013023
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013024 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013025 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013026 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013027
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013028 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013029 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013030 ReplaceInstUsesWith(*I, C);
13031
Chris Lattner62b14df2002-09-02 04:59:56 +000013032 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013033 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013034 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013035 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013036 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013037 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013038
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013039 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013040 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013041 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13042 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013043 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13044 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013045 if (NewC != CE) {
13046 i->set(NewC);
13047 Changed = true;
13048 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013049 }
13050
Chris Lattnerea1c4542004-12-08 23:43:58 +000013051 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013052 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013053 BasicBlock *BB = I->getParent();
13054 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13055 if (UserParent != BB) {
13056 bool UserIsSuccessor = false;
13057 // See if the user is one of our successors.
13058 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13059 if (*SI == UserParent) {
13060 UserIsSuccessor = true;
13061 break;
13062 }
13063
13064 // If the user is one of our immediate successors, and if that successor
13065 // only has us as a predecessors (we'd have to split the critical edge
13066 // otherwise), we can keep going.
13067 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13068 next(pred_begin(UserParent)) == pred_end(UserParent))
13069 // Okay, the CFG is simple enough, try to sink this instruction.
13070 Changed |= TryToSinkInstruction(I, UserParent);
13071 }
13072 }
13073
Chris Lattner8a2a3112001-12-14 16:52:21 +000013074 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013075#ifndef NDEBUG
13076 std::string OrigI;
13077#endif
13078 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013079 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013080 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013081 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013082 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013083 DOUT << "IC: Old = " << *I
13084 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013085
Chris Lattnerf523d062004-06-09 05:08:07 +000013086 // Everything uses the new instruction now.
13087 I->replaceAllUsesWith(Result);
13088
13089 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013090 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013091 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013092
Chris Lattner6934a042007-02-11 01:23:03 +000013093 // Move the name to the new instruction first.
13094 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013095
13096 // Insert the new instruction into the basic block...
13097 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013098 BasicBlock::iterator InsertPos = I;
13099
13100 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13101 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13102 ++InsertPos;
13103
13104 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013105
Chris Lattner00d51312004-05-01 23:27:23 +000013106 // Make sure that we reprocess all operands now that we reduced their
13107 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013108 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013109
Chris Lattnerf523d062004-06-09 05:08:07 +000013110 // Instructions can end up on the worklist more than once. Make sure
13111 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013112 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013113
13114 // Erase the old instruction.
13115 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013116 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013117#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013118 DOUT << "IC: Mod = " << OrigI
13119 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013120#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013121
Chris Lattner90ac28c2002-08-02 19:29:35 +000013122 // If the instruction was modified, it's possible that it is now dead.
13123 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013124 if (isInstructionTriviallyDead(I)) {
13125 // Make sure we process all operands now that we are reducing their
13126 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013127 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013128
Chris Lattner00d51312004-05-01 23:27:23 +000013129 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013130 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013131 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013132 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013133 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013134 AddToWorkList(I);
13135 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013136 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013137 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013138 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013139 }
13140 }
13141
Chris Lattnerec9c3582007-03-03 02:04:50 +000013142 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013143
13144 // Do an explicit clear, this shrinks the map if needed.
13145 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013146 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013147}
13148
Chris Lattnerec9c3582007-03-03 02:04:50 +000013149
13150bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013151 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013152 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013153
Chris Lattnerec9c3582007-03-03 02:04:50 +000013154 bool EverMadeChange = false;
13155
13156 // Iterate while there is work to do.
13157 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013158 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013159 EverMadeChange = true;
13160 return EverMadeChange;
13161}
13162
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013163FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013164 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013165}