blob: a6538dcaa23335fda733a03f208851846d1b8a20 [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 Andersond672ecb2009-07-03 00:17:18 +0000150 *i = Context->getUndef(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
Reid Spencere4d87aa2006-12-23 06:05:41 +0000216 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
217 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 Andersond672ecb2009-07-03 00:17:18 +0000289 return Context->getConstantExprCast(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 Andersond672ecb2009-07-03 00:17:18 +0000315 I.replaceAllUsesWith(Context->getUndef(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 Andersond672ecb2009-07-03 00:17:18 +0000522 Constant *Folded = Context->getConstantExpr(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 Andersond672ecb2009-07-03 00:17:18 +0000535 Constant *Folded = Context->getConstantExpr(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 Andersond672ecb2009-07-03 00:17:18 +0000569 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000573 return Context->getConstantExprNeg(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 Andersond672ecb2009-07-03 00:17:18 +0000588 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000592 return Context->getConstantExprFNeg(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
Chris Lattner574da9b2005-01-13 20:14:25 +0000631/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
632/// expression, return it.
633static User *dyn_castGetElementPtr(Value *V) {
634 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
635 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
636 if (CE->getOpcode() == Instruction::GetElementPtr)
637 return cast<User>(V);
638 return false;
639}
640
Reid Spencer7177c3a2007-03-25 05:33:51 +0000641/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000642static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000643 return Context->getConstantExprAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000644 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000645}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000646/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000647static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000648 return Context->getConstantExprSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000649 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000650}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000651/// MultiplyOverflows - True if the multiply can not be expressed in an int
652/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000653static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000654 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000655 uint32_t W = C1->getBitWidth();
656 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
657 if (sign) {
658 LHSExt.sext(W * 2);
659 RHSExt.sext(W * 2);
660 } else {
661 LHSExt.zext(W * 2);
662 RHSExt.zext(W * 2);
663 }
664
665 APInt MulExt = LHSExt * RHSExt;
666
667 if (sign) {
668 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670 return MulExt.slt(Min) || MulExt.sgt(Max);
671 } else
672 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673}
Chris Lattner955f3312004-09-28 21:48:02 +0000674
Reid Spencere7816b52007-03-08 01:52:58 +0000675
Chris Lattner255d8912006-02-11 09:31:47 +0000676/// ShrinkDemandedConstant - Check to see if the specified operand of the
677/// specified instruction is a constant integer. If so, check to see if there
678/// are any bits set in the constant that are not demanded. If so, shrink the
679/// constant and return true.
680static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000681 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000682 assert(I && "No instruction?");
683 assert(OpNo < I->getNumOperands() && "Operand index too large");
684
685 // If the operand is not a constant integer, nothing to do.
686 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687 if (!OpC) return false;
688
689 // If there are no bits set that aren't demanded, nothing to do.
690 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691 if ((~Demanded & OpC->getValue()) == 0)
692 return false;
693
694 // This instruction is producing bits that are not demanded. Shrink the RHS.
695 Demanded &= OpC->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +0000696 I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000697 return true;
698}
699
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000700// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
701// set of known zero and one bits, compute the maximum and minimum values that
702// could have the specified known zero and known one bits, returning them in
703// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000704static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000707 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708 KnownZero.getBitWidth() == Min.getBitWidth() &&
709 KnownZero.getBitWidth() == Max.getBitWidth() &&
710 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000711 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714 // bit if it is unknown.
715 Min = KnownOne;
716 Max = KnownOne|UnknownBits;
717
Dan Gohman1c8491e2009-04-25 17:12:48 +0000718 if (UnknownBits.isNegative()) { // Sign bit is unknown
719 Min.set(Min.getBitWidth()-1);
720 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722}
723
724// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725// a set of known zero and one bits, compute the maximum and minimum values that
726// could have the specified known zero and known one bits, returning them in
727// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000734 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000735 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736
737 // The minimum value is when the unknown bits are all zeros.
738 Min = KnownOne;
739 // The maximum value is when the unknown bits are all ones.
740 Max = KnownOne|UnknownBits;
741}
Chris Lattner255d8912006-02-11 09:31:47 +0000742
Chris Lattner886ab6c2009-01-31 08:15:18 +0000743/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744/// SimplifyDemandedBits knows about. See if the instruction has any
745/// properties that allow us to simplify its operands.
746bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000747 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000748 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
750
751 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
752 KnownZero, KnownOne, 0);
753 if (V == 0) return false;
754 if (V == &Inst) return true;
755 ReplaceInstUsesWith(Inst, V);
756 return true;
757}
758
759/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760/// specified instruction operand if possible, updating it in place. It returns
761/// true if it made any change and false otherwise.
762bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
763 APInt &KnownZero, APInt &KnownOne,
764 unsigned Depth) {
765 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766 KnownZero, KnownOne, Depth);
767 if (NewVal == 0) return false;
768 U.set(NewVal);
769 return true;
770}
771
772
773/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000775/// that only the bits set in DemandedMask of the result of V are ever used
776/// downstream. Consequently, depending on the mask and V, it may be possible
777/// to replace V with a constant or one of its operands. In such cases, this
778/// function does the replacement and returns true. In all other cases, it
779/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000780/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000781/// to be zero in the expression. These are provided to potentially allow the
782/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783/// the expression. KnownOne and KnownZero always follow the invariant that
784/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785/// the bits in KnownOne and KnownZero may only be accurate for those bits set
786/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000788///
789/// This returns null if it did not change anything and it permits no
790/// simplification. This returns V itself if it did some simplification of V's
791/// operands based on the information about what bits are demanded. This returns
792/// some other non-null value if it found out that V is equal to another value
793/// in the context where the specified bits are demanded, but not for all users.
794Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795 APInt &KnownZero, APInt &KnownOne,
796 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000797 assert(V != 0 && "Null pointer of Value???");
798 assert(Depth <= 6 && "Limit Search Depth");
799 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000800 const Type *VTy = V->getType();
801 assert((TD || !isa<PointerType>(VTy)) &&
802 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000803 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804 (!VTy->isIntOrIntVector() ||
805 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000806 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000807 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000808 "Value *V, DemandedMask, KnownZero and KnownOne "
809 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811 // We know all of the bits for a constant!
812 KnownOne = CI->getValue() & DemandedMask;
813 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000815 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000816 if (isa<ConstantPointerNull>(V)) {
817 // We know all of the bits for a constant!
818 KnownOne.clear();
819 KnownZero = DemandedMask;
820 return 0;
821 }
822
Chris Lattner08d2cc72009-01-31 07:26:06 +0000823 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000824 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000825 if (DemandedMask == 0) { // Not demanding any bits from V.
826 if (isa<UndefValue>(V))
827 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000828 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000829 }
830
Chris Lattner4598c942009-01-31 08:24:16 +0000831 if (Depth == 6) // Limit search depth.
832 return 0;
833
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000834 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
836
Dan Gohman1c8491e2009-04-25 17:12:48 +0000837 Instruction *I = dyn_cast<Instruction>(V);
838 if (!I) {
839 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840 return 0; // Only analyze instructions.
841 }
842
Chris Lattner4598c942009-01-31 08:24:16 +0000843 // If there are multiple uses of this value and we aren't at the root, then
844 // we can't do any simplifications of the operands, because DemandedMask
845 // only reflects the bits demanded by *one* of the users.
846 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000847 // Despite the fact that we can't simplify this instruction in all User's
848 // context, we can at least compute the knownzero/knownone bits, and we can
849 // do simplifications that apply to *just* the one user if we know that
850 // this instruction has a simpler value in that context.
851 if (I->getOpcode() == Instruction::And) {
852 // If either the LHS or the RHS are Zero, the result is zero.
853 ComputeMaskedBits(I->getOperand(1), DemandedMask,
854 RHSKnownZero, RHSKnownOne, Depth+1);
855 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856 LHSKnownZero, LHSKnownOne, Depth+1);
857
858 // If all of the demanded bits are known 1 on one side, return the other.
859 // These bits cannot contribute to the result of the 'and' in this
860 // context.
861 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
862 (DemandedMask & ~LHSKnownZero))
863 return I->getOperand(0);
864 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
865 (DemandedMask & ~RHSKnownZero))
866 return I->getOperand(1);
867
868 // If all of the demanded bits in the inputs are known zeros, return zero.
869 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000870 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000871
872 } else if (I->getOpcode() == Instruction::Or) {
873 // We can simplify (X|Y) -> X or Y in the user's context if we know that
874 // only bits from X or Y are demanded.
875
876 // If either the LHS or the RHS are One, the result is One.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
880 LHSKnownZero, LHSKnownOne, Depth+1);
881
882 // If all of the demanded bits are known zero on one side, return the
883 // other. These bits cannot contribute to the result of the 'or' in this
884 // context.
885 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
886 (DemandedMask & ~LHSKnownOne))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
889 (DemandedMask & ~RHSKnownOne))
890 return I->getOperand(1);
891
892 // If all of the potentially set bits on one side are known to be set on
893 // the other side, just use the 'other' side.
894 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
895 (DemandedMask & (~RHSKnownZero)))
896 return I->getOperand(0);
897 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
898 (DemandedMask & (~LHSKnownZero)))
899 return I->getOperand(1);
900 }
901
Chris Lattner4598c942009-01-31 08:24:16 +0000902 // Compute the KnownZero/KnownOne bits to simplify things downstream.
903 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904 return 0;
905 }
906
907 // If this is the root being simplified, allow it to have multiple uses,
908 // just set the DemandedMask to all bits so that we can try to simplify the
909 // operands. This allows visitTruncInst (for example) to simplify the
910 // operand of a trunc without duplicating all the logic below.
911 if (Depth == 0 && !V->hasOneUse())
912 DemandedMask = APInt::getAllOnesValue(BitWidth);
913
Reid Spencer8cb68342007-03-12 17:25:59 +0000914 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000915 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000916 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000917 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000918 case Instruction::And:
919 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921 RHSKnownZero, RHSKnownOne, Depth+1) ||
922 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I;
925 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
926 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000927
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and'.
930 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
931 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
934 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If all of the demanded bits in the inputs are known zeros, return zero.
938 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000939 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000942 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000944
945 // Output known-1 bits are only known if set in both the LHS & RHS.
946 RHSKnownOne &= LHSKnownOne;
947 // Output known-0 are known to be clear if zero in either the LHS | RHS.
948 RHSKnownZero |= LHSKnownZero;
949 break;
950 case Instruction::Or:
951 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1) ||
954 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I;
957 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
958 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'or'.
962 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
963 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
966 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000968
969 // If all of the potentially set bits on one side are known to be set on
970 // the other side, just use the 'other' side.
971 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
972 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
975 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000979 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // Output known-0 bits are only known if clear in both the LHS & RHS.
983 RHSKnownZero &= LHSKnownZero;
984 // Output known-1 are known to be set if set in either the LHS | RHS.
985 RHSKnownOne |= LHSKnownOne;
986 break;
987 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000995
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'xor'.
998 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001002
1003 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1005 (RHSKnownOne & LHSKnownOne);
1006 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1008 (RHSKnownOne & LHSKnownZero);
1009
1010 // If all of the demanded bits are known to be zero on one side or the
1011 // other, turn this into an *inclusive* or.
1012 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1013 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1014 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001015 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001016 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001017 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018 }
1019
1020 // If all of the demanded bits on one side are known, and all of the set
1021 // bits on that side are also known to be set on the other side, turn this
1022 // into an AND, as we know the bits will be cleared.
1023 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1024 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1025 // all known
1026 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001027 Constant *AndC = ConstantInt::get(*Context,
1028 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001030 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001031 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001032 }
1033 }
1034
1035 // If the RHS is a constant, see if we can simplify it.
1036 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001037 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001039
1040 RHSKnownZero = KnownZeroOut;
1041 RHSKnownOne = KnownOneOut;
1042 break;
1043 }
1044 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1046 RHSKnownZero, RHSKnownOne, Depth+1) ||
1047 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I;
1050 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1051 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001052
1053 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001054 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1055 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057
1058 // Only known if known in both the LHS and RHS.
1059 RHSKnownOne &= LHSKnownOne;
1060 RHSKnownZero &= LHSKnownZero;
1061 break;
1062 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001063 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001064 DemandedMask.zext(truncBf);
1065 RHSKnownZero.zext(truncBf);
1066 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001068 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 DemandedMask.trunc(BitWidth);
1071 RHSKnownZero.trunc(BitWidth);
1072 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001074 break;
1075 }
1076 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001077 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001079
1080 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1081 if (const VectorType *SrcVTy =
1082 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1083 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1084 // Don't touch a bitcast between vectors of different element counts.
1085 return false;
1086 } else
1087 // Don't touch a scalar-to-vector bitcast.
1088 return false;
1089 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1090 // Don't touch a vector-to-scalar bitcast.
1091 return false;
1092
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001095 return I;
1096 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 break;
1098 case Instruction::ZExt: {
1099 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001100 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001101
Zhou Shengd48653a2007-03-29 04:45:55 +00001102 DemandedMask.trunc(SrcBitWidth);
1103 RHSKnownZero.trunc(SrcBitWidth);
1104 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 DemandedMask.zext(BitWidth);
1109 RHSKnownZero.zext(BitWidth);
1110 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001113 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001114 break;
1115 }
1116 case Instruction::SExt: {
1117 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001118 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
Reid Spencer8cb68342007-03-12 17:25:59 +00001120 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001121 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001122
Zhou Sheng01542f32007-03-29 02:26:30 +00001123 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 // If any of the sign extended bits are demanded, we know that the sign
1125 // bit is demanded.
1126 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001127 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001128
Zhou Shengd48653a2007-03-29 04:45:55 +00001129 InputDemandedBits.trunc(SrcBitWidth);
1130 RHSKnownZero.trunc(SrcBitWidth);
1131 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001132 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001133 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 InputDemandedBits.zext(BitWidth);
1136 RHSKnownZero.zext(BitWidth);
1137 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001138 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001139
1140 // If the sign bit of the input is known set or clear, then we know the
1141 // top bits of the result.
1142
1143 // If the input sign bit is known zero, or if the NewBits are not demanded
1144 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1148 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001149 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 }
1152 break;
1153 }
1154 case Instruction::Add: {
1155 // Figure out what the input bits are. If the top bits of the and result
1156 // are not demanded, then the add doesn't demand them from its input
1157 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001159
1160 // If there is a constant on the RHS, there are a variety of xformations
1161 // we can do.
1162 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163 // If null, this should be simplified elsewhere. Some of the xforms here
1164 // won't work if the RHS is zero.
1165 if (RHS->isZero())
1166 break;
1167
1168 // If the top bit of the output is demanded, demand everything from the
1169 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001170 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001175 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // If the RHS of the add has bits set that can't affect the input, reduce
1178 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001179 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // Avoid excess work.
1183 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1184 break;
1185
1186 // Turn it into OR if input bits are zero.
1187 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1188 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001189 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 }
1193
1194 // We can say something about the output known-zero and known-one bits,
1195 // depending on potential carries from the input constant and the
1196 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1197 // bits set and the RHS constant is 0x01001, then we know we have a known
1198 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1199
1200 // To compute this, we first compute the potential carry bits. These are
1201 // the bits which may be modified. I'm not aware of a better way to do
1202 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001203 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001204 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001205
1206 // Now that we know which bits have carries, compute the known-1/0 sets.
1207
1208 // Bits are known one if they are known zero in one operand and one in the
1209 // other, and there is no input carry.
1210 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1211 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1212
1213 // Bits are known zero if they are known zero in both operands and there
1214 // is no input carry.
1215 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1216 } else {
1217 // If the high-bits of this ADD are not demanded, then it does not demand
1218 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001220 // Right fill the mask of bits for this ADD to demand the most
1221 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001222 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001223 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1224 LHSKnownZero, LHSKnownOne, Depth+1) ||
1225 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 }
1229 }
1230 break;
1231 }
1232 case Instruction::Sub:
1233 // If the high-bits of this SUB are not demanded, then it does not demand
1234 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001235 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 // Right fill the mask of bits for this SUB to demand the most
1237 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001238 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001239 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1241 LHSKnownZero, LHSKnownOne, Depth+1) ||
1242 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001244 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001246 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1247 // the known zeros and ones.
1248 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 break;
1250 case Instruction::Shl:
1251 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001252 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001253 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
1257 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 RHSKnownZero <<= ShiftAmt;
1259 RHSKnownOne <<= ShiftAmt;
1260 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001261 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001262 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 }
1264 break;
1265 case Instruction::LShr:
1266 // For a logical shift right
1267 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001268 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001269
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001271 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001274 return I;
1275 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1277 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001278 if (ShiftAmt) {
1279 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001280 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001281 RHSKnownZero |= HighBits; // high bits known zero.
1282 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 }
1284 break;
1285 case Instruction::AShr:
1286 // If this is an arithmetic shift right and only the low-bit is set, we can
1287 // always convert this into a logical shr, even if the shift amount is
1288 // variable. The low bit of the shift cannot be an input sign bit unless
1289 // the shift amount is >= the size of the datatype, which is undefined.
1290 if (DemandedMask == 1) {
1291 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001292 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001296
1297 // If the sign bit is the only bit demanded by this ashr, then there is no
1298 // need to do it, the shift doesn't change the high bit.
1299 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
1302 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001303 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001304
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001306 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001307 // If any of the "high bits" are demanded, we should set the sign bit as
1308 // demanded.
1309 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1310 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001313 return I;
1314 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1319
1320 // Handle the sign bits.
1321 APInt SignBit(APInt::getSignBit(BitWidth));
1322 // Adjust to where it is now in the mask.
1323 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1324
1325 // If the input sign bit is known to be zero, or if none of the top bits
1326 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001327 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 (HighBits & ~DemandedMask) == HighBits) {
1329 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001330 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1334 RHSKnownOne |= HighBits;
1335 }
1336 }
1337 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001338 case Instruction::SRem:
1339 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001340 APInt RA = Rem->getValue().abs();
1341 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001342 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001344
Nick Lewycky8e394322008-11-02 02:41:50 +00001345 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350
1351 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1352 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353
1354 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357 }
1358 }
1359 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001360 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001361 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1362 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001363 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1364 KnownZero2, KnownOne2, Depth+1) ||
1365 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001366 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001368
Chris Lattner455e9ab2009-01-21 18:09:24 +00001369 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001370 Leaders = std::max(Leaders,
1371 KnownZero2.countLeadingOnes());
1372 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001373 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001375 case Instruction::Call:
1376 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1377 switch (II->getIntrinsicID()) {
1378 default: break;
1379 case Intrinsic::bswap: {
1380 // If the only bits demanded come from one byte of the bswap result,
1381 // just shift the input byte into position to eliminate the bswap.
1382 unsigned NLZ = DemandedMask.countLeadingZeros();
1383 unsigned NTZ = DemandedMask.countTrailingZeros();
1384
1385 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1386 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1387 // have 14 leading zeros, round to 8.
1388 NLZ &= ~7;
1389 NTZ &= ~7;
1390 // If we need exactly one byte, we can do this transformation.
1391 if (BitWidth-NLZ-NTZ == 8) {
1392 unsigned ResultBit = NTZ;
1393 unsigned InputBit = BitWidth-NTZ-8;
1394
1395 // Replace this with either a left or right shift to get the byte into
1396 // the right place.
1397 Instruction *NewVal;
1398 if (InputBit > ResultBit)
1399 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001400 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001401 else
1402 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001403 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001404 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001405 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001406 }
1407
1408 // TODO: Could compute known zero/one bits based on the input.
1409 break;
1410 }
1411 }
1412 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001413 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001414 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001415 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001416
1417 // If the client is only demanding bits that we know, return the known
1418 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001420 Constant *C = ConstantInt::get(*Context, RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001421 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001422 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001423 return C;
1424 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 return false;
1426}
1427
Chris Lattner867b99f2006-10-05 06:55:50 +00001428
Mon P Wangaeb06d22008-11-10 04:46:22 +00001429/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001430/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001431/// actually used by the caller. This method analyzes which elements of the
1432/// operand are undef and returns that information in UndefElts.
1433///
1434/// If the information about demanded elements can be used to simplify the
1435/// operation, the operation is simplified, then the resultant value is
1436/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001437Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1438 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001439 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001441 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001442 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001443
1444 if (isa<UndefValue>(V)) {
1445 // If the entire vector is undefined, just return this info.
1446 UndefElts = EltMask;
1447 return 0;
1448 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1449 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001450 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001452
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001454 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1455 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001456 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001457
1458 std::vector<Constant*> Elts;
1459 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001460 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001462 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1464 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001465 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 } else { // Otherwise, defined.
1467 Elts.push_back(CP->getOperand(i));
1468 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001469
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001471 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 return NewCP != CP ? NewCP : 0;
1473 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001474 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001476
1477 // Check if this is identity. If so, return 0 since we are not simplifying
1478 // anything.
1479 if (DemandedElts == ((1ULL << VWidth) -1))
1480 return 0;
1481
Reid Spencer9d6565a2007-02-15 02:26:10 +00001482 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001483 Constant *Zero = Context->getNullValue(EltTy);
1484 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001486 for (unsigned i = 0; i != VWidth; ++i) {
1487 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1488 Elts.push_back(Elt);
1489 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001491 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 }
1493
Dan Gohman488fbfc2008-09-09 18:11:14 +00001494 // Limit search depth.
1495 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001496 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001497
1498 // If multiple users are using the root value, procede with
1499 // simplification conservatively assuming that all elements
1500 // are needed.
1501 if (!V->hasOneUse()) {
1502 // Quit if we find multiple users of a non-root value though.
1503 // They'll be handled when it's their turn to be visited by
1504 // the main instcombine process.
1505 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001506 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001507 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001508
1509 // Conservatively assume that all elements are needed.
1510 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 }
1512
1513 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001514 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001515
1516 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001517 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 Value *TmpV;
1519 switch (I->getOpcode()) {
1520 default: break;
1521
1522 case Instruction::InsertElement: {
1523 // If this is a variable index, we don't know which element it overwrites.
1524 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001525 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 if (Idx == 0) {
1527 // Note that we can't propagate undef elt info, because we don't know
1528 // which elt is getting updated.
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530 UndefElts2, Depth+1);
1531 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532 break;
1533 }
1534
1535 // If this is inserting an element that isn't demanded, remove this
1536 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001537 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001538 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001539 return AddSoonDeadInstToWorklist(*I, 0);
1540
1541 // Otherwise, the element inserted overwrites whatever was there, so the
1542 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001543 APInt DemandedElts2 = DemandedElts;
1544 DemandedElts2.clear(IdxNo);
1545 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001546 UndefElts, Depth+1);
1547 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1548
1549 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001550 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001551 break;
1552 }
1553 case Instruction::ShuffleVector: {
1554 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001555 uint64_t LHSVWidth =
1556 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001557 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001559 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 unsigned MaskVal = Shuffle->getMaskValue(i);
1561 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001562 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001564 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001565 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 else
Evan Cheng388df622009-02-03 10:05:09 +00001567 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 }
1569 }
1570 }
1571
Nate Begeman7b254672009-02-11 22:36:25 +00001572 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001574 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1576
Nate Begeman7b254672009-02-11 22:36:25 +00001577 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1579 UndefElts3, Depth+1);
1580 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1581
1582 bool NewUndefElts = false;
1583 for (unsigned i = 0; i < VWidth; i++) {
1584 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001585 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001586 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001587 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001588 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001589 NewUndefElts = true;
1590 UndefElts.set(i);
1591 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001592 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001593 if (UndefElts3[MaskVal - LHSVWidth]) {
1594 NewUndefElts = true;
1595 UndefElts.set(i);
1596 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 }
1598 }
1599
1600 if (NewUndefElts) {
1601 // Add additional discovered undefs.
1602 std::vector<Constant*> Elts;
1603 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001604 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001605 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001606 else
Owen Andersoneed707b2009-07-24 23:12:02 +00001607 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001608 Shuffle->getMaskValue(i)));
1609 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001610 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001611 MadeChange = true;
1612 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001613 break;
1614 }
Chris Lattner69878332007-04-14 22:29:23 +00001615 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001616 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001617 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1618 if (!VTy) break;
1619 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001620 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001621 unsigned Ratio;
1622
1623 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001624 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001625 // elements as are demanded of us.
1626 Ratio = 1;
1627 InputDemandedElts = DemandedElts;
1628 } else if (VWidth > InVWidth) {
1629 // Untested so far.
1630 break;
1631
1632 // If there are more elements in the result than there are in the source,
1633 // then an input element is live if any of the corresponding output
1634 // elements are live.
1635 Ratio = VWidth/InVWidth;
1636 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001637 if (DemandedElts[OutIdx])
1638 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001639 }
1640 } else {
1641 // Untested so far.
1642 break;
1643
1644 // If there are more elements in the source than there are in the result,
1645 // then an input element is live if the corresponding output element is
1646 // live.
1647 Ratio = InVWidth/VWidth;
1648 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001649 if (DemandedElts[InIdx/Ratio])
1650 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001651 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001652
Chris Lattner69878332007-04-14 22:29:23 +00001653 // div/rem demand all inputs, because they don't want divide by zero.
1654 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1655 UndefElts2, Depth+1);
1656 if (TmpV) {
1657 I->setOperand(0, TmpV);
1658 MadeChange = true;
1659 }
1660
1661 UndefElts = UndefElts2;
1662 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001663 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001664 // If there are more elements in the result than there are in the source,
1665 // then an output element is undef if the corresponding input element is
1666 // undef.
1667 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001668 if (UndefElts2[OutIdx/Ratio])
1669 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001670 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001671 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001672 // If there are more elements in the source than there are in the result,
1673 // then a result element is undef if all of the corresponding input
1674 // elements are undef.
1675 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1676 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001677 if (!UndefElts2[InIdx]) // Not undef?
1678 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001679 }
1680 break;
1681 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001682 case Instruction::And:
1683 case Instruction::Or:
1684 case Instruction::Xor:
1685 case Instruction::Add:
1686 case Instruction::Sub:
1687 case Instruction::Mul:
1688 // div/rem demand all inputs, because they don't want divide by zero.
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1690 UndefElts, Depth+1);
1691 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1692 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1693 UndefElts2, Depth+1);
1694 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1695
1696 // Output elements are undefined if both are undefined. Consider things
1697 // like undef&0. The result is known zero, not undef.
1698 UndefElts &= UndefElts2;
1699 break;
1700
1701 case Instruction::Call: {
1702 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1703 if (!II) break;
1704 switch (II->getIntrinsicID()) {
1705 default: break;
1706
1707 // Binary vector operations that work column-wise. A dest element is a
1708 // function of the corresponding input elements from the two inputs.
1709 case Intrinsic::x86_sse_sub_ss:
1710 case Intrinsic::x86_sse_mul_ss:
1711 case Intrinsic::x86_sse_min_ss:
1712 case Intrinsic::x86_sse_max_ss:
1713 case Intrinsic::x86_sse2_sub_sd:
1714 case Intrinsic::x86_sse2_mul_sd:
1715 case Intrinsic::x86_sse2_min_sd:
1716 case Intrinsic::x86_sse2_max_sd:
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1718 UndefElts, Depth+1);
1719 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1720 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1721 UndefElts2, Depth+1);
1722 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1723
1724 // If only the low elt is demanded and this is a scalarizable intrinsic,
1725 // scalarize it now.
1726 if (DemandedElts == 1) {
1727 switch (II->getIntrinsicID()) {
1728 default: break;
1729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse_mul_ss:
1731 case Intrinsic::x86_sse2_sub_sd:
1732 case Intrinsic::x86_sse2_mul_sd:
1733 // TODO: Lower MIN/MAX/ABS/etc
1734 Value *LHS = II->getOperand(1);
1735 Value *RHS = II->getOperand(2);
1736 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001737 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001738 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001739 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001740 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001741
1742 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001743 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001744 case Intrinsic::x86_sse_sub_ss:
1745 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 II->getName()), *II);
1748 break;
1749 case Intrinsic::x86_sse_mul_ss:
1750 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001751 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001752 II->getName()), *II);
1753 break;
1754 }
1755
1756 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001757 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001758 Context->getUndef(II->getType()), TmpV,
Owen Andersoneed707b2009-07-24 23:12:02 +00001759 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001760 InsertNewInstBefore(New, *II);
1761 AddSoonDeadInstToWorklist(*II, 0);
1762 return New;
1763 }
1764 }
1765
1766 // Output elements are undefined if both are undefined. Consider things
1767 // like undef&0. The result is known zero, not undef.
1768 UndefElts &= UndefElts2;
1769 break;
1770 }
1771 break;
1772 }
1773 }
1774 return MadeChange ? I : 0;
1775}
1776
Dan Gohman45b4e482008-05-19 22:14:15 +00001777
Chris Lattner564a7272003-08-13 19:01:45 +00001778/// AssociativeOpt - Perform an optimization on an associative operator. This
1779/// function is designed to check a chain of associative operators for a
1780/// potential to apply a certain optimization. Since the optimization may be
1781/// applicable if the expression was reassociated, this checks the chain, then
1782/// reassociates the expression as necessary to expose the optimization
1783/// opportunity. This makes use of a special Functor, which must define
1784/// 'shouldApply' and 'apply' methods.
1785///
1786template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001787static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001788 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001789 unsigned Opcode = Root.getOpcode();
1790 Value *LHS = Root.getOperand(0);
1791
1792 // Quick check, see if the immediate LHS matches...
1793 if (F.shouldApply(LHS))
1794 return F.apply(Root);
1795
1796 // Otherwise, if the LHS is not of the same opcode as the root, return.
1797 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001798 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001799 // Should we apply this transform to the RHS?
1800 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1801
1802 // If not to the RHS, check to see if we should apply to the LHS...
1803 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1804 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1805 ShouldApply = true;
1806 }
1807
1808 // If the functor wants to apply the optimization to the RHS of LHSI,
1809 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1810 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001811 // Now all of the instructions are in the current basic block, go ahead
1812 // and perform the reassociation.
1813 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1814
1815 // First move the selected RHS to the LHS of the root...
1816 Root.setOperand(0, LHSI->getOperand(1));
1817
1818 // Make what used to be the LHS of the root be the user of the root...
1819 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001820 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001821 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001822 return 0;
1823 }
Chris Lattner65725312004-04-16 18:08:07 +00001824 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001825 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001826 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001827 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001828 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001829
1830 // Now propagate the ExtraOperand down the chain of instructions until we
1831 // get to LHSI.
1832 while (TmpLHSI != LHSI) {
1833 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001834 // Move the instruction to immediately before the chain we are
1835 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001836 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001837 ARI = NextLHSI;
1838
Chris Lattner564a7272003-08-13 19:01:45 +00001839 Value *NextOp = NextLHSI->getOperand(1);
1840 NextLHSI->setOperand(1, ExtraOperand);
1841 TmpLHSI = NextLHSI;
1842 ExtraOperand = NextOp;
1843 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001844
Chris Lattner564a7272003-08-13 19:01:45 +00001845 // Now that the instructions are reassociated, have the functor perform
1846 // the transformation...
1847 return F.apply(Root);
1848 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001849
Chris Lattner564a7272003-08-13 19:01:45 +00001850 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1851 }
1852 return 0;
1853}
1854
Dan Gohman844731a2008-05-13 00:00:25 +00001855namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001856
Nick Lewycky02d639f2008-05-23 04:34:58 +00001857// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001858struct AddRHS {
1859 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001860 LLVMContext *Context;
1861 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001862 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1863 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001864 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001865 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001866 }
1867};
1868
1869// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1870// iff C1&C2 == 0
1871struct AddMaskingAnd {
1872 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001873 LLVMContext *Context;
1874 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001875 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001876 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001877 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001878 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001879 }
1880 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001881 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001882 }
1883};
1884
Dan Gohman844731a2008-05-13 00:00:25 +00001885}
1886
Chris Lattner6e7ba452005-01-01 16:22:27 +00001887static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001888 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001889 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001890
Reid Spencer3da59db2006-11-27 01:05:10 +00001891 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001892 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001893 }
1894
Chris Lattner2eefe512004-04-09 19:05:30 +00001895 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001898
Chris Lattner2eefe512004-04-09 19:05:30 +00001899 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1900 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001901 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1902 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001903 }
1904
1905 Value *Op0 = SO, *Op1 = ConstOperand;
1906 if (!ConstIsRHS)
1907 std::swap(Op0, Op1);
1908 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001910 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001911 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001912 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1913 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001914 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001915 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001916 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001917 return IC->InsertNewInstBefore(New, I);
1918}
1919
1920// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1921// constant as the other operand, try to fold the binary operator into the
1922// select arguments. This also works for Cast instructions, which obviously do
1923// not have a second operand.
1924static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1925 InstCombiner *IC) {
1926 // Don't modify shared select instructions
1927 if (!SI->hasOneUse()) return 0;
1928 Value *TV = SI->getOperand(1);
1929 Value *FV = SI->getOperand(2);
1930
1931 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001932 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001933 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001934
Chris Lattner6e7ba452005-01-01 16:22:27 +00001935 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1936 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1937
Gabor Greif051a9502008-04-06 20:25:17 +00001938 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1939 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001940 }
1941 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001942}
1943
Chris Lattner4e998b22004-09-29 05:07:12 +00001944
1945/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1946/// node as operand #0, see if we can fold the instruction into the PHI (which
1947/// is only possible if all operands to the PHI are constants).
1948Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1949 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001950 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001951 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001952
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001953 // Check to see if all of the operands of the PHI are constants. If there is
1954 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001955 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 BasicBlock *NonConstBB = 0;
1957 for (unsigned i = 0; i != NumPHIValues; ++i)
1958 if (!isa<Constant>(PN->getIncomingValue(i))) {
1959 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001960 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 NonConstBB = PN->getIncomingBlock(i);
1962
1963 // If the incoming non-constant value is in I's block, we have an infinite
1964 // loop.
1965 if (NonConstBB == I.getParent())
1966 return 0;
1967 }
1968
1969 // If there is exactly one non-constant value, we can insert a copy of the
1970 // operation in that block. However, if this is a critical edge, we would be
1971 // inserting the computation one some other paths (e.g. inside a loop). Only
1972 // do this if the pred block is unconditionally branching into the phi block.
1973 if (NonConstBB) {
1974 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1975 if (!BI || !BI->isUnconditional()) return 0;
1976 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001977
1978 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001979 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001980 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001981 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001982 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001983
1984 // Next, add all of the operands to the PHI.
1985 if (I.getNumOperands() == 2) {
1986 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001987 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001988 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001990 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00001991 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001993 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001994 } else {
1995 assert(PN->getIncomingBlock(i) == NonConstBB);
1996 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001997 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001998 PN->getIncomingValue(i), C, "phitmp",
1999 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002000 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002001 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002002 CI->getPredicate(),
2003 PN->getIncomingValue(i), C, "phitmp",
2004 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002005 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002006 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002007
Chris Lattnerdbab3862007-03-02 21:28:56 +00002008 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002009 }
2010 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002011 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002012 } else {
2013 CastInst *CI = cast<CastInst>(&I);
2014 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002015 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002016 Value *InV;
2017 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002018 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019 } else {
2020 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002021 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002022 I.getType(), "phitmp",
2023 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002024 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002025 }
2026 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002027 }
2028 }
2029 return ReplaceInstUsesWith(I, NewPN);
2030}
2031
Chris Lattner2454a2e2008-01-29 06:52:45 +00002032
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002033/// WillNotOverflowSignedAdd - Return true if we can prove that:
2034/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2035/// This basically requires proving that the add in the original type would not
2036/// overflow to change the sign bit or have a carry out.
2037bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2038 // There are different heuristics we can use for this. Here are some simple
2039 // ones.
2040
2041 // Add has the property that adding any two 2's complement numbers can only
2042 // have one carry bit which can change a sign. As such, if LHS and RHS each
2043 // have at least two sign bits, we know that the addition of the two values will
2044 // sign extend fine.
2045 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2046 return true;
2047
2048
2049 // If one of the operands only has one non-zero bit, and if the other operand
2050 // has a known-zero bit in a more significant place than it (not including the
2051 // sign bit) the ripple may go up to and fill the zero, but won't change the
2052 // sign. For example, (X & ~4) + 1.
2053
2054 // TODO: Implement.
2055
2056 return false;
2057}
2058
Chris Lattner2454a2e2008-01-29 06:52:45 +00002059
Chris Lattner7e708292002-06-25 16:13:24 +00002060Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002061 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002062 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002063
Chris Lattner66331a42004-04-10 22:01:55 +00002064 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002065 // X + undef -> undef
2066 if (isa<UndefValue>(RHS))
2067 return ReplaceInstUsesWith(I, RHS);
2068
Chris Lattner66331a42004-04-10 22:01:55 +00002069 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002070 if (RHSC->isNullValue())
2071 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002072
Chris Lattner66331a42004-04-10 22:01:55 +00002073 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002074 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002075 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002076 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002077 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002078 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002079
2080 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2081 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002082 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002083 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002084
Eli Friedman709b33d2009-07-13 22:27:52 +00002085 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002086 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002087 if (ZI->getSrcTy() == Type::Int1Ty)
2088 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002089 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002090
2091 if (isa<PHINode>(LHS))
2092 if (Instruction *NV = FoldOpIntoPhi(I))
2093 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002094
Chris Lattner4f637d42006-01-06 17:59:59 +00002095 ConstantInt *XorRHS = 0;
2096 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002097 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002098 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002099 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002100 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002101
Zhou Sheng4351c642007-04-02 08:20:41 +00002102 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002103 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2104 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002105 do {
2106 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002107 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2108 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002109 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2110 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002111 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002112 if (!MaskedValueIsZero(XorLHS,
2113 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002114 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002115 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002116 }
2117 }
2118 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002119 C0080Val = APIntOps::lshr(C0080Val, Size);
2120 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2121 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002122
Reid Spencer35c38852007-03-28 01:36:16 +00002123 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002124 // with funny bit widths then this switch statement should be removed. It
2125 // is just here to get the size of the "middle" type back up to something
2126 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002127 const Type *MiddleType = 0;
2128 switch (Size) {
2129 default: break;
2130 case 32: MiddleType = Type::Int32Ty; break;
2131 case 16: MiddleType = Type::Int16Ty; break;
2132 case 8: MiddleType = Type::Int8Ty; break;
2133 }
2134 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002135 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002136 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002137 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002138 }
2139 }
Chris Lattner66331a42004-04-10 22:01:55 +00002140 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002141
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002142 if (I.getType() == Type::Int1Ty)
2143 return BinaryOperator::CreateXor(LHS, RHS);
2144
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002145 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002146 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002147 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2148 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002149
2150 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2151 if (RHSI->getOpcode() == Instruction::Sub)
2152 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2153 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2154 }
2155 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2156 if (LHSI->getOpcode() == Instruction::Sub)
2157 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2158 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2159 }
Robert Bocchino71698282004-07-27 21:02:21 +00002160 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002161
Chris Lattner5c4afb92002-05-08 22:46:53 +00002162 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002163 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002164 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002165 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002166 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002167 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002168 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002169 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002170 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002171 }
2172
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002173 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002174 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002175
2176 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002177 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002178 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002180
Misha Brukmanfd939082005-04-21 23:48:37 +00002181
Chris Lattner50af16a2004-11-13 19:50:12 +00002182 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002183 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002184 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002185 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002186
2187 // X*C1 + X*C2 --> X * (C1+C2)
2188 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002189 if (X == dyn_castFoldableMul(RHS, C1, Context))
2190 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002191 }
2192
2193 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002194 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2195 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002196
Chris Lattnere617c9e2007-01-05 02:17:46 +00002197 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002198 if (dyn_castNotVal(LHS, Context) == RHS ||
2199 dyn_castNotVal(RHS, Context) == LHS)
2200 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002201
Chris Lattnerad3448c2003-02-18 19:57:07 +00002202
Chris Lattner564a7272003-08-13 19:01:45 +00002203 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002204 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002205 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002206 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002207
2208 // A+B --> A|B iff A and B have no bits set in common.
2209 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2210 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2211 APInt LHSKnownOne(IT->getBitWidth(), 0);
2212 APInt LHSKnownZero(IT->getBitWidth(), 0);
2213 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2214 if (LHSKnownZero != 0) {
2215 APInt RHSKnownOne(IT->getBitWidth(), 0);
2216 APInt RHSKnownZero(IT->getBitWidth(), 0);
2217 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2218
2219 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002220 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002221 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002222 }
2223 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002224
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002225 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002226 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002227 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002228 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2229 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002230 if (W != Y) {
2231 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002232 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002233 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002234 std::swap(W, X);
2235 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002236 std::swap(Y, Z);
2237 std::swap(W, X);
2238 }
2239 }
2240
2241 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002242 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002243 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002244 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002245 }
2246 }
2247 }
2248
Chris Lattner6b032052003-10-02 15:11:26 +00002249 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002250 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002251 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002252 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002253
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002255 if (LHS->hasOneUse() &&
2256 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002257 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258 if (Anded == CRHS) {
2259 // See if all bits from the first bit set in the Add RHS up are included
2260 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002261 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262
2263 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002264 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002265
2266 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002267 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002268
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2270 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002271 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002272 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002273 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002274 }
2275 }
2276 }
2277
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002278 // Try to fold constant add into select arguments.
2279 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002280 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002281 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002282 }
2283
Chris Lattner42790482007-12-20 01:56:58 +00002284 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002285 {
2286 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288 if (!SI) {
2289 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002290 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291 }
Chris Lattner42790482007-12-20 01:56:58 +00002292 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002293 Value *TV = SI->getTrueValue();
2294 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002295 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002296
2297 // Can we fold the add into the argument of the select?
2298 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002299 if (match(FV, m_Zero(), *Context) &&
2300 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002301 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002302 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002303 if (match(TV, m_Zero(), *Context) &&
2304 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002305 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002306 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002307 }
2308 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002309
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002310 // Check for (add (sext x), y), see if we can merge this into an
2311 // integer add followed by a sext.
2312 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2313 // (add (sext x), cst) --> (sext (add x, cst'))
2314 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2315 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002316 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002317 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002318 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002319 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2320 // Insert the new, smaller add.
2321 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2322 CI, "addconv");
2323 InsertNewInstBefore(NewAdd, I);
2324 return new SExtInst(NewAdd, I.getType());
2325 }
2326 }
2327
2328 // (add (sext x), (sext y)) --> (sext (add int x, y))
2329 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2330 // Only do this if x/y have the same type, if at last one of them has a
2331 // single use (so we don't increase the number of sexts), and if the
2332 // integer add will not overflow.
2333 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2334 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2335 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2336 RHSConv->getOperand(0))) {
2337 // Insert the new integer add.
2338 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2339 RHSConv->getOperand(0),
2340 "addconv");
2341 InsertNewInstBefore(NewAdd, I);
2342 return new SExtInst(NewAdd, I.getType());
2343 }
2344 }
2345 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002346
2347 return Changed ? &I : 0;
2348}
2349
2350Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2351 bool Changed = SimplifyCommutative(I);
2352 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2353
2354 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2355 // X + 0 --> X
2356 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002357 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002358 (I.getType())->getValueAPF()))
2359 return ReplaceInstUsesWith(I, LHS);
2360 }
2361
2362 if (isa<PHINode>(LHS))
2363 if (Instruction *NV = FoldOpIntoPhi(I))
2364 return NV;
2365 }
2366
2367 // -A + B --> B - A
2368 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002369 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002370 return BinaryOperator::CreateFSub(RHS, LHSV);
2371
2372 // A + -B --> A - B
2373 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002374 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002375 return BinaryOperator::CreateFSub(LHS, V);
2376
2377 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2378 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2379 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2380 return ReplaceInstUsesWith(I, LHS);
2381
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002382 // Check for (add double (sitofp x), y), see if we can merge this into an
2383 // integer add followed by a promotion.
2384 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2385 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2386 // ... if the constant fits in the integer value. This is useful for things
2387 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2388 // requires a constant pool load, and generally allows the add to be better
2389 // instcombined.
2390 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2391 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002392 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002393 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002394 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002395 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2396 // Insert the new integer add.
2397 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2398 CI, "addconv");
2399 InsertNewInstBefore(NewAdd, I);
2400 return new SIToFPInst(NewAdd, I.getType());
2401 }
2402 }
2403
2404 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2405 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2406 // Only do this if x/y have the same type, if at last one of them has a
2407 // single use (so we don't increase the number of int->fp conversions),
2408 // and if the integer add will not overflow.
2409 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2410 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2411 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2412 RHSConv->getOperand(0))) {
2413 // Insert the new integer add.
2414 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2415 RHSConv->getOperand(0),
2416 "addconv");
2417 InsertNewInstBefore(NewAdd, I);
2418 return new SIToFPInst(NewAdd, I.getType());
2419 }
2420 }
2421 }
2422
Chris Lattner7e708292002-06-25 16:13:24 +00002423 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002424}
2425
Chris Lattner7e708292002-06-25 16:13:24 +00002426Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002427 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002428
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002429 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002430 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002431
Chris Lattner233f7dc2002-08-12 21:17:25 +00002432 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002433 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002434 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002435
Chris Lattnere87597f2004-10-16 18:11:37 +00002436 if (isa<UndefValue>(Op0))
2437 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2438 if (isa<UndefValue>(Op1))
2439 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2440
Chris Lattnerd65460f2003-11-05 01:06:05 +00002441 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2442 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002443 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002444 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002445
Chris Lattnerd65460f2003-11-05 01:06:05 +00002446 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002447 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002448 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002449 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002450
Chris Lattner76b7a062007-01-15 07:02:54 +00002451 // -(X >>u 31) -> (X >>s 31)
2452 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002453 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002454 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002455 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002456 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002457 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002458 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002459 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002460 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002461 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002462 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002463 }
2464 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002465 }
2466 else if (SI->getOpcode() == Instruction::AShr) {
2467 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2468 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002469 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002470 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002471 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002473 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002474 }
2475 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002476 }
2477 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002478 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002479
2480 // Try to fold constant sub into select arguments.
2481 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002483 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002484
2485 // C - zext(bool) -> bool ? C - 1 : C
2486 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2487 if (ZI->getSrcTy() == Type::Int1Ty)
2488 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002489 }
2490
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002491 if (I.getType() == Type::Int1Ty)
2492 return BinaryOperator::CreateXor(Op0, Op1);
2493
Chris Lattner43d84d62005-04-07 16:15:25 +00002494 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002495 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002496 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002497 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2498 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002499 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002500 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2501 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002502 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2503 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2504 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002505 return BinaryOperator::CreateSub(
2506 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002507 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002508 }
2509
Chris Lattnerfd059242003-10-15 16:48:29 +00002510 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002511 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2512 // is not used by anyone else...
2513 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002514 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002515 // Swap the two operands of the subexpr...
2516 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2517 Op1I->setOperand(0, IIOp1);
2518 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002519
Chris Lattnera2881962003-02-18 19:28:33 +00002520 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002521 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002522 }
2523
2524 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2525 //
2526 if (Op1I->getOpcode() == Instruction::And &&
2527 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2528 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2529
Chris Lattnerf523d062004-06-09 05:08:07 +00002530 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002531 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2532 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002533 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002534 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002535
Reid Spencerac5209e2006-10-16 23:08:08 +00002536 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002537 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002538 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002539 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002540 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002541 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002542 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002543
Chris Lattnerad3448c2003-02-18 19:57:07 +00002544 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002545 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002546 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2547 Constant *CP1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00002548 Context->getConstantExprSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002549 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002550 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002551 }
Chris Lattner40371712002-05-09 01:29:19 +00002552 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002553 }
Chris Lattnera2881962003-02-18 19:28:33 +00002554
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002555 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2556 if (Op0I->getOpcode() == Instruction::Add) {
2557 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2558 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2559 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2560 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2561 } else if (Op0I->getOpcode() == Instruction::Sub) {
2562 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002563 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2564 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002565 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002566 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002567
Chris Lattner50af16a2004-11-13 19:50:12 +00002568 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002569 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002570 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002571 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002572
Chris Lattner50af16a2004-11-13 19:50:12 +00002573 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002574 if (X == dyn_castFoldableMul(Op1, C2, Context))
2575 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002576 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002577 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002578}
2579
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2581 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2582
2583 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002584 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002585 return BinaryOperator::CreateFAdd(Op0, V);
2586
2587 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2588 if (Op1I->getOpcode() == Instruction::FAdd) {
2589 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002590 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2591 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002593 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2594 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002595 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002596 }
2597
2598 return 0;
2599}
2600
Chris Lattnera0141b92007-07-15 20:42:37 +00002601/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2602/// comparison only checks the sign bit. If it only checks the sign bit, set
2603/// TrueIfSigned if the result of the comparison is true when the input value is
2604/// signed.
2605static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2606 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002607 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002608 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2609 TrueIfSigned = true;
2610 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002611 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2612 TrueIfSigned = true;
2613 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002614 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2615 TrueIfSigned = false;
2616 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002617 case ICmpInst::ICMP_UGT:
2618 // True if LHS u> RHS and RHS == high-bit-mask - 1
2619 TrueIfSigned = true;
2620 return RHS->getValue() ==
2621 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2622 case ICmpInst::ICMP_UGE:
2623 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2624 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002625 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002626 default:
2627 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002628 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002629}
2630
Chris Lattner7e708292002-06-25 16:13:24 +00002631Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002632 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002633 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002634
Eli Friedman1694e092009-07-18 09:12:15 +00002635 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002636 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002637
Chris Lattner233f7dc2002-08-12 21:17:25 +00002638 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002639 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2640 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002641
2642 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002643 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002644 if (SI->getOpcode() == Instruction::Shl)
2645 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002646 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002647 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002648
Zhou Sheng843f07672007-04-19 05:39:12 +00002649 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002650 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2651 if (CI->equalsInt(1)) // X * 1 == X
2652 return ReplaceInstUsesWith(I, Op0);
2653 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002654 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002655
Zhou Sheng97b52c22007-03-29 01:57:21 +00002656 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002657 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002659 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002660 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002661 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002662 if (Op1->isNullValue())
2663 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002664
2665 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2666 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002667 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002668
2669 // As above, vector X*splat(1.0) -> X in all defined cases.
2670 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002671 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2672 if (CI->equalsInt(1))
2673 return ReplaceInstUsesWith(I, Op0);
2674 }
2675 }
Chris Lattnera2881962003-02-18 19:28:33 +00002676 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002677
2678 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2679 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002680 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002681 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002682 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002683 Op1, "tmp");
2684 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002685 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002686 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002687 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002688
2689 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002690
2691 // Try to fold constant mul into select arguments.
2692 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002693 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002694 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002695
2696 if (isa<PHINode>(Op0))
2697 if (Instruction *NV = FoldOpIntoPhi(I))
2698 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002699 }
2700
Owen Andersond672ecb2009-07-03 00:17:18 +00002701 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2702 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002703 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002704
Nick Lewycky0c730792008-11-21 07:33:58 +00002705 // (X / Y) * Y = X - (X % Y)
2706 // (X / Y) * -Y = (X % Y) - X
2707 {
2708 Value *Op1 = I.getOperand(1);
2709 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2710 if (!BO ||
2711 (BO->getOpcode() != Instruction::UDiv &&
2712 BO->getOpcode() != Instruction::SDiv)) {
2713 Op1 = Op0;
2714 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2715 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002716 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002717 if (BO && BO->hasOneUse() &&
2718 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2719 (BO->getOpcode() == Instruction::UDiv ||
2720 BO->getOpcode() == Instruction::SDiv)) {
2721 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2722
2723 Instruction *Rem;
2724 if (BO->getOpcode() == Instruction::UDiv)
2725 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2726 else
2727 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2728
2729 InsertNewInstBefore(Rem, I);
2730 Rem->takeName(BO);
2731
2732 if (Op1BO == Op1)
2733 return BinaryOperator::CreateSub(Op0BO, Rem);
2734 else
2735 return BinaryOperator::CreateSub(Rem, Op0BO);
2736 }
2737 }
2738
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002739 if (I.getType() == Type::Int1Ty)
2740 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2741
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002742 // If one of the operands of the multiply is a cast from a boolean value, then
2743 // we know the bool is either zero or one, so this is a 'masking' multiply.
2744 // See if we can simplify things based on how the boolean was originally
2745 // formed.
2746 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002747 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002748 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002749 BoolCast = CI;
2750 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002751 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002752 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002753 BoolCast = CI;
2754 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002755 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002756 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2757 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002758 bool TIS = false;
2759
Reid Spencere4d87aa2006-12-23 06:05:41 +00002760 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002761 // multiply into a shift/and combination.
2762 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002763 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2764 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002765 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002766 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002767 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002768 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002769 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002771 BoolCast->getOperand(0)->getName()+
2772 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002773
2774 // If the multiply type is not the same as the source type, sign extend
2775 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002776 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002777 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2778 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002779 Instruction::CastOps opcode =
2780 (SrcBits == DstBits ? Instruction::BitCast :
2781 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2782 V = InsertCastBefore(opcode, V, I.getType(), I);
2783 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002784
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002785 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002786 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002787 }
2788 }
2789 }
2790
Chris Lattner7e708292002-06-25 16:13:24 +00002791 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002792}
2793
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002794Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2795 bool Changed = SimplifyCommutative(I);
2796 Value *Op0 = I.getOperand(0);
2797
2798 // Simplify mul instructions with a constant RHS...
2799 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2800 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2801 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2802 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2803 if (Op1F->isExactlyValue(1.0))
2804 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2805 } else if (isa<VectorType>(Op1->getType())) {
2806 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2807 // As above, vector X*splat(1.0) -> X in all defined cases.
2808 if (Constant *Splat = Op1V->getSplatValue()) {
2809 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2810 if (F->isExactlyValue(1.0))
2811 return ReplaceInstUsesWith(I, Op0);
2812 }
2813 }
2814 }
2815
2816 // Try to fold constant mul into select arguments.
2817 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2818 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2819 return R;
2820
2821 if (isa<PHINode>(Op0))
2822 if (Instruction *NV = FoldOpIntoPhi(I))
2823 return NV;
2824 }
2825
Owen Andersond672ecb2009-07-03 00:17:18 +00002826 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2827 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002828 return BinaryOperator::CreateFMul(Op0v, Op1v);
2829
2830 return Changed ? &I : 0;
2831}
2832
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002833/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2834/// instruction.
2835bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2836 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2837
2838 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2839 int NonNullOperand = -1;
2840 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2841 if (ST->isNullValue())
2842 NonNullOperand = 2;
2843 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2844 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2845 if (ST->isNullValue())
2846 NonNullOperand = 1;
2847
2848 if (NonNullOperand == -1)
2849 return false;
2850
2851 Value *SelectCond = SI->getOperand(0);
2852
2853 // Change the div/rem to use 'Y' instead of the select.
2854 I.setOperand(1, SI->getOperand(NonNullOperand));
2855
2856 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2857 // problem. However, the select, or the condition of the select may have
2858 // multiple uses. Based on our knowledge that the operand must be non-zero,
2859 // propagate the known value for the select into other uses of it, and
2860 // propagate a known value of the condition into its other users.
2861
2862 // If the select and condition only have a single use, don't bother with this,
2863 // early exit.
2864 if (SI->use_empty() && SelectCond->hasOneUse())
2865 return true;
2866
2867 // Scan the current block backward, looking for other uses of SI.
2868 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2869
2870 while (BBI != BBFront) {
2871 --BBI;
2872 // If we found a call to a function, we can't assume it will return, so
2873 // information from below it cannot be propagated above it.
2874 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2875 break;
2876
2877 // Replace uses of the select or its condition with the known values.
2878 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2879 I != E; ++I) {
2880 if (*I == SI) {
2881 *I = SI->getOperand(NonNullOperand);
2882 AddToWorkList(BBI);
2883 } else if (*I == SelectCond) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00002884 *I = NonNullOperand == 1 ? Context->getTrue() :
2885 Context->getFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002886 AddToWorkList(BBI);
2887 }
2888 }
2889
2890 // If we past the instruction, quit looking for it.
2891 if (&*BBI == SI)
2892 SI = 0;
2893 if (&*BBI == SelectCond)
2894 SelectCond = 0;
2895
2896 // If we ran out of things to eliminate, break out of the loop.
2897 if (SelectCond == 0 && SI == 0)
2898 break;
2899
2900 }
2901 return true;
2902}
2903
2904
Reid Spencer1628cec2006-10-26 06:15:43 +00002905/// This function implements the transforms on div instructions that work
2906/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2907/// used by the visitors to those instructions.
2908/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002909Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002910 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002911
Chris Lattner50b2ca42008-02-19 06:12:18 +00002912 // undef / X -> 0 for integer.
2913 // undef / X -> undef for FP (the undef could be a snan).
2914 if (isa<UndefValue>(Op0)) {
2915 if (Op0->getType()->isFPOrFPVector())
2916 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002917 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002918 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002919
2920 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002921 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002922 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002923
Reid Spencer1628cec2006-10-26 06:15:43 +00002924 return 0;
2925}
Misha Brukmanfd939082005-04-21 23:48:37 +00002926
Reid Spencer1628cec2006-10-26 06:15:43 +00002927/// This function implements the transforms common to both integer division
2928/// instructions (udiv and sdiv). It is called by the visitors to those integer
2929/// division instructions.
2930/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002931Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2933
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002934 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002935 if (Op0 == Op1) {
2936 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002937 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002938 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002939 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002940 }
2941
Owen Andersoneed707b2009-07-24 23:12:02 +00002942 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002943 return ReplaceInstUsesWith(I, CI);
2944 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002945
Reid Spencer1628cec2006-10-26 06:15:43 +00002946 if (Instruction *Common = commonDivTransforms(I))
2947 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002948
2949 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2950 // This does not apply for fdiv.
2951 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2952 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002953
2954 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2955 // div X, 1 == X
2956 if (RHS->equalsInt(1))
2957 return ReplaceInstUsesWith(I, Op0);
2958
2959 // (X / C1) / C2 -> X / (C1*C2)
2960 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2961 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2962 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002963 if (MultiplyOverflows(RHS, LHSRHS,
2964 I.getOpcode()==Instruction::SDiv, Context))
2965 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002966 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002967 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002968 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002969 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002970
Reid Spencerbca0e382007-03-23 20:05:17 +00002971 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002972 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2973 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2974 return R;
2975 if (isa<PHINode>(Op0))
2976 if (Instruction *NV = FoldOpIntoPhi(I))
2977 return NV;
2978 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002979 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002980
Chris Lattnera2881962003-02-18 19:28:33 +00002981 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002982 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002983 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00002984 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002985
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002986 // It can't be division by zero, hence it must be division by one.
2987 if (I.getType() == Type::Int1Ty)
2988 return ReplaceInstUsesWith(I, Op0);
2989
Nick Lewycky895f0852008-11-27 20:21:08 +00002990 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2991 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2992 // div X, 1 == X
2993 if (X->isOne())
2994 return ReplaceInstUsesWith(I, Op0);
2995 }
2996
Reid Spencer1628cec2006-10-26 06:15:43 +00002997 return 0;
2998}
2999
3000Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3002
3003 // Handle the integer div common cases
3004 if (Instruction *Common = commonIDivTransforms(I))
3005 return Common;
3006
Reid Spencer1628cec2006-10-26 06:15:43 +00003007 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003008 // X udiv C^2 -> X >> C
3009 // Check to see if this is an unsigned division with an exact power of 2,
3010 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003011 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003012 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003013 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003014
3015 // X udiv C, where C >= signbit
3016 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003017 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3018 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003019 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003020 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003021 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003022 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 }
3024
3025 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003026 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003027 if (RHSI->getOpcode() == Instruction::Shl &&
3028 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003029 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003030 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003031 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003032 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003033 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003034 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003035 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003036 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003037 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003038 }
3039 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003040 }
3041
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3043 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003044 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003045 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003047 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003048 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003049 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003050 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003051 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003052 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003053 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003054 Op0, TC, SI->getName()+".t");
3055 TSI = InsertNewInstBefore(TSI, I);
3056
3057 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003058 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003059 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003060 Op0, FC, SI->getName()+".f");
3061 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003062
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003063 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003064 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003065 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003066 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003067 return 0;
3068}
3069
Reid Spencer1628cec2006-10-26 06:15:43 +00003070Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3071 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3072
3073 // Handle the integer div common cases
3074 if (Instruction *Common = commonIDivTransforms(I))
3075 return Common;
3076
3077 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3078 // sdiv X, -1 == -X
3079 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003080 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 }
3082
3083 // If the sign bits of both operands are zero (i.e. we can prove they are
3084 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003085 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003086 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003087 if (MaskedValueIsZero(Op0, Mask)) {
3088 if (MaskedValueIsZero(Op1, Mask)) {
3089 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3090 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3091 }
3092 ConstantInt *ShiftedInt;
3093 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3094 ShiftedInt->getValue().isPowerOf2()) {
3095 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3096 // Safe because the only negative value (1 << Y) can take on is
3097 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3098 // the sign bit set.
3099 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3100 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 }
Eli Friedman8be17392009-07-18 09:53:21 +00003102 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003103
3104 return 0;
3105}
3106
3107Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108 return commonDivTransforms(I);
3109}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110
Reid Spencer0a783f72006-11-02 01:53:59 +00003111/// This function implements the transforms on rem instructions that work
3112/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3113/// is used by the visitors to those instructions.
3114/// @brief Transforms common to all three rem instructions
3115Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003117
Chris Lattner50b2ca42008-02-19 06:12:18 +00003118 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3119 if (I.getType()->isFPOrFPVector())
3120 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003121 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003122 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003123 if (isa<UndefValue>(Op1))
3124 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003125
3126 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003127 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003129
Reid Spencer0a783f72006-11-02 01:53:59 +00003130 return 0;
3131}
3132
3133/// This function implements the transforms common to both integer remainder
3134/// instructions (urem and srem). It is called by the visitors to those integer
3135/// remainder instructions.
3136/// @brief Common integer remainder transforms
3137Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140 if (Instruction *common = commonRemTransforms(I))
3141 return common;
3142
Dale Johannesened6af242009-01-21 00:35:19 +00003143 // 0 % X == 0 for integer, we don't need to preserve faults!
3144 if (Constant *LHS = dyn_cast<Constant>(Op0))
3145 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003146 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003147
Chris Lattner857e8cd2004-12-12 21:48:58 +00003148 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003149 // X % 0 == undef, we don't need to preserve faults!
3150 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003151 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003152
Chris Lattnera2881962003-02-18 19:28:33 +00003153 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003154 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003155
Chris Lattner97943922006-02-28 05:49:21 +00003156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159 return R;
3160 } else if (isa<PHINode>(Op0I)) {
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003164
3165 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003166 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003167 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003168 }
Chris Lattnera2881962003-02-18 19:28:33 +00003169 }
3170
Reid Spencer0a783f72006-11-02 01:53:59 +00003171 return 0;
3172}
3173
3174Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177 if (Instruction *common = commonIRemTransforms(I))
3178 return common;
3179
3180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181 // X urem C^2 -> X and C
3182 // Check to see if this is an unsigned remainder with an exact power of 2,
3183 // if so, convert to a bitwise and.
3184 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003185 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003186 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003187 }
3188
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003189 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3191 if (RHSI->getOpcode() == Instruction::Shl &&
3192 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003193 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003194 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003195 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003196 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003197 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003198 }
3199 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003200 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003201
Reid Spencer0a783f72006-11-02 01:53:59 +00003202 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3203 // where C1&C2 are powers of two.
3204 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3205 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3206 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3207 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003208 if ((STO->getValue().isPowerOf2()) &&
3209 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003211 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3212 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003213 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003214 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3215 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003216 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003217 }
3218 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003219 }
3220
Chris Lattner3f5b8772002-05-06 16:14:14 +00003221 return 0;
3222}
3223
Reid Spencer0a783f72006-11-02 01:53:59 +00003224Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3226
Dan Gohmancff55092007-11-05 23:16:33 +00003227 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003228 if (Instruction *common = commonIRemTransforms(I))
3229 return common;
3230
Owen Andersond672ecb2009-07-03 00:17:18 +00003231 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003232 if (!isa<Constant>(RHSNeg) ||
3233 (isa<ConstantInt>(RHSNeg) &&
3234 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003235 // X % -Y -> X % Y
3236 AddUsesToWorkList(I);
3237 I.setOperand(1, RHSNeg);
3238 return &I;
3239 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003240
Dan Gohmancff55092007-11-05 23:16:33 +00003241 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003243 if (I.getType()->isInteger()) {
3244 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3245 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3246 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003247 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003248 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 }
3250
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003251 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003252 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3253 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003254
Nick Lewycky9dce8732008-12-20 16:48:00 +00003255 bool hasNegative = false;
3256 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3257 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3258 if (RHS->getValue().isNegative())
3259 hasNegative = true;
3260
3261 if (hasNegative) {
3262 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003263 for (unsigned i = 0; i != VWidth; ++i) {
3264 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3265 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003266 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003267 else
3268 Elts[i] = RHS;
3269 }
3270 }
3271
Owen Andersond672ecb2009-07-03 00:17:18 +00003272 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003273 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003274 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003275 I.setOperand(1, NewRHSV);
3276 return &I;
3277 }
3278 }
3279 }
3280
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 return 0;
3282}
3283
3284Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003285 return commonRemTransforms(I);
3286}
3287
Chris Lattner457dd822004-06-09 07:59:58 +00003288// isOneBitSet - Return true if there is exactly one bit set in the specified
3289// constant.
3290static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003291 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003292}
3293
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003294// isHighOnes - Return true if the constant is of the form 1+0+.
3295// This is the same as lowones(~X).
3296static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003297 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003298}
3299
Reid Spencere4d87aa2006-12-23 06:05:41 +00003300/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003301/// are carefully arranged to allow folding of expressions such as:
3302///
3303/// (A < B) | (A > B) --> (A != B)
3304///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003305/// Note that this is only valid if the first and second predicates have the
3306/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003307///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003308/// Three bits are used to represent the condition, as follows:
3309/// 0 A > B
3310/// 1 A == B
3311/// 2 A < B
3312///
3313/// <=> Value Definition
3314/// 000 0 Always false
3315/// 001 1 A > B
3316/// 010 2 A == B
3317/// 011 3 A >= B
3318/// 100 4 A < B
3319/// 101 5 A != B
3320/// 110 6 A <= B
3321/// 111 7 Always true
3322///
3323static unsigned getICmpCode(const ICmpInst *ICI) {
3324 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003325 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003326 case ICmpInst::ICMP_UGT: return 1; // 001
3327 case ICmpInst::ICMP_SGT: return 1; // 001
3328 case ICmpInst::ICMP_EQ: return 2; // 010
3329 case ICmpInst::ICMP_UGE: return 3; // 011
3330 case ICmpInst::ICMP_SGE: return 3; // 011
3331 case ICmpInst::ICMP_ULT: return 4; // 100
3332 case ICmpInst::ICMP_SLT: return 4; // 100
3333 case ICmpInst::ICMP_NE: return 5; // 101
3334 case ICmpInst::ICMP_ULE: return 6; // 110
3335 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003336 // True -> 7
3337 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003338 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003339 return 0;
3340 }
3341}
3342
Evan Cheng8db90722008-10-14 17:15:11 +00003343/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3344/// predicate into a three bit mask. It also returns whether it is an ordered
3345/// predicate by reference.
3346static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3347 isOrdered = false;
3348 switch (CC) {
3349 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3350 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003351 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3352 case FCmpInst::FCMP_UGT: return 1; // 001
3353 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3354 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003355 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3356 case FCmpInst::FCMP_UGE: return 3; // 011
3357 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3358 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003359 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3360 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003361 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3362 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003363 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003364 default:
3365 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003366 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003367 return 0;
3368 }
3369}
3370
Reid Spencere4d87aa2006-12-23 06:05:41 +00003371/// getICmpValue - This is the complement of getICmpCode, which turns an
3372/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003373/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003374/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003375static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003376 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003377 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003378 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersonb3056fa2009-07-21 18:03:38 +00003379 case 0: return Context->getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380 case 1:
3381 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003382 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 else
Owen Anderson333c4002009-07-09 23:48:35 +00003384 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3385 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 case 3:
3387 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003388 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, 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_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 case 4:
3392 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003393 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 else
Owen Anderson333c4002009-07-09 23:48:35 +00003395 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3396 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 case 6:
3398 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003399 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 else
Owen Anderson333c4002009-07-09 23:48:35 +00003401 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003402 case 7: return Context->getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003403 }
3404}
3405
Evan Cheng8db90722008-10-14 17:15:11 +00003406/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3407/// opcode and two operands into either a FCmp instruction. isordered is passed
3408/// in to determine which kind of predicate to use in the new fcmp instruction.
3409static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003410 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003411 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003412 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003413 case 0:
3414 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 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_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003418 case 1:
3419 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003421 else
Owen Anderson333c4002009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003423 case 2:
3424 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003426 else
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 case 3:
3429 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, 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_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 case 4:
3434 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003436 else
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003438 case 5:
3439 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003441 else
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003443 case 6:
3444 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003445 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003446 else
Owen Anderson333c4002009-07-09 23:48:35 +00003447 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003448 case 7: return Context->getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003449 }
3450}
3451
Chris Lattnerb9553d62008-11-16 04:55:20 +00003452/// PredicatesFoldable - Return true if both predicates match sign or if at
3453/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3455 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003456 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3457 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458}
3459
3460namespace {
3461// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3462struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003463 InstCombiner &IC;
3464 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 ICmpInst::Predicate pred;
3466 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3467 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3468 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003469 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003470 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3471 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003472 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3473 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003474 return false;
3475 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003476 Instruction *apply(Instruction &Log) const {
3477 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3478 if (ICI->getOperand(0) != LHS) {
3479 assert(ICI->getOperand(1) == LHS);
3480 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 }
3482
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003483 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003484 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003485 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003486 unsigned Code;
3487 switch (Log.getOpcode()) {
3488 case Instruction::And: Code = LHSCode & RHSCode; break;
3489 case Instruction::Or: Code = LHSCode | RHSCode; break;
3490 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003491 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003492 }
3493
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003494 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3495 ICmpInst::isSignedPredicate(ICI->getPredicate());
3496
Owen Andersond672ecb2009-07-03 00:17:18 +00003497 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003498 if (Instruction *I = dyn_cast<Instruction>(RV))
3499 return I;
3500 // Otherwise, it's a constant boolean value...
3501 return IC.ReplaceInstUsesWith(Log, RV);
3502 }
3503};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003504} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003505
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003506// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3507// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003508// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003510 ConstantInt *OpRHS,
3511 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003512 BinaryOperator &TheAnd) {
3513 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003514 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003515 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003516 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003517
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 switch (Op->getOpcode()) {
3519 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003520 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003522 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003524 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003525 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003526 }
3527 break;
3528 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003529 if (Together == AndRHS) // (X | C) & C --> C
3530 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003531
Chris Lattner6e7ba452005-01-01 16:22:27 +00003532 if (Op->hasOneUse() && Together != OpRHS) {
3533 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003534 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003535 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003536 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 }
3539 break;
3540 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003541 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 // Adding a one to a single bit bit-field should be turned into an XOR
3543 // of the bit. First thing to check is to see if this AND is with a
3544 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003545 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546
3547 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003548 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Ok, at this point, we know that we are masking the result of the
3550 // ADD down to exactly one bit. If the constant we are adding has
3551 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003552 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003553
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003554 // Check to see if any bits below the one bit set in AndRHSV are set.
3555 if ((AddRHS & (AndRHSV-1)) == 0) {
3556 // If not, the only thing that can effect the output of the AND is
3557 // the bit specified by AndRHSV. If that bit is set, the effect of
3558 // the XOR is to toggle the bit. If it is clear, then the ADD has
3559 // no effect.
3560 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3561 TheAnd.setOperand(0, X);
3562 return &TheAnd;
3563 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003567 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003568 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 }
3570 }
3571 }
3572 }
3573 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003574
3575 case Instruction::Shl: {
3576 // We know that the AND will not produce any of the bits shifted in, so if
3577 // the anded constant includes them, clear them now!
3578 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003579 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003580 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003582 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003583
Zhou Sheng290bec52007-03-29 08:15:12 +00003584 if (CI->getValue() == ShlMask) {
3585 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003586 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3587 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003588 TheAnd.setOperand(1, CI);
3589 return &TheAnd;
3590 }
3591 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003592 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003593 case Instruction::LShr:
3594 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003595 // We know that the AND will not produce any of the bits shifted in, so if
3596 // the anded constant includes them, clear them now! This only applies to
3597 // unsigned shifts, because a signed shr may bring in set bits!
3598 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003602 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003603
Zhou Sheng290bec52007-03-29 08:15:12 +00003604 if (CI->getValue() == ShrMask) {
3605 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003606 return ReplaceInstUsesWith(TheAnd, Op);
3607 } else if (CI != AndRHS) {
3608 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3609 return &TheAnd;
3610 }
3611 break;
3612 }
3613 case Instruction::AShr:
3614 // Signed shr.
3615 // See if this is shifting in some sign extension, then masking it out
3616 // with an and.
3617 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003618 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003619 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003620 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003621 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003622 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003623 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003624 // Make the argument unsigned.
3625 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003626 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003627 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003628 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003629 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003630 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003631 }
3632 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003633 }
3634 return 0;
3635}
3636
Chris Lattner8b170942002-08-09 23:47:40 +00003637
Chris Lattnera96879a2004-09-29 17:40:11 +00003638/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3639/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3641/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003642/// insert new instructions.
3643Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644 bool isSigned, bool Inside,
3645 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003646 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003647 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003648 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649
Chris Lattnera96879a2004-09-29 17:40:11 +00003650 if (Inside) {
3651 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003652 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003653
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003655 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003656 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003658 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659 }
3660
3661 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003662 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003663 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003664 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003665 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003666 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003667 }
3668
3669 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003670 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003671
Reid Spencere4e40032007-03-21 23:19:50 +00003672 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003673 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003674 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675 ICmpInst::Predicate pred = (isSigned ?
3676 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003677 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003679
Reid Spencere4e40032007-03-21 23:19:50 +00003680 // Emit V-Lo >u Hi-1-Lo
3681 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003682 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003683 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003684 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003685 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003686 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003687}
3688
Chris Lattner7203e152005-09-18 07:22:02 +00003689// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3690// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3691// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3692// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003693static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003694 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003695 uint32_t BitWidth = Val->getType()->getBitWidth();
3696 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003697
3698 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003699 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003700 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003701 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003702 return true;
3703}
3704
Chris Lattner7203e152005-09-18 07:22:02 +00003705/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3706/// where isSub determines whether the operator is a sub. If we can fold one of
3707/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003708///
3709/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3710/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3711/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3712///
3713/// return (A +/- B).
3714///
3715Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003716 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003717 Instruction &I) {
3718 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3719 if (!LHSI || LHSI->getNumOperands() != 2 ||
3720 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3721
3722 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3723
3724 switch (LHSI->getOpcode()) {
3725 default: return 0;
3726 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003727 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003728 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003729 if ((Mask->getValue().countLeadingZeros() +
3730 Mask->getValue().countPopulation()) ==
3731 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003732 break;
3733
3734 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3735 // part, we don't need any explicit masks to take them out of A. If that
3736 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003737 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003738 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003739 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003740 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003741 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003742 break;
3743 }
3744 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003745 return 0;
3746 case Instruction::Or:
3747 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003748 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003749 if ((Mask->getValue().countLeadingZeros() +
3750 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003751 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003752 break;
3753 return 0;
3754 }
3755
3756 Instruction *New;
3757 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003758 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003759 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003760 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003761 return InsertNewInstBefore(New, I);
3762}
3763
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003764/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3765Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3766 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003767 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003768 ConstantInt *LHSCst, *RHSCst;
3769 ICmpInst::Predicate LHSCC, RHSCC;
3770
Chris Lattnerea065fb2008-11-16 05:10:52 +00003771 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003772 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3773 m_ConstantInt(LHSCst)), *Context) ||
3774 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3775 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003776 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003777
3778 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3779 // where C is a power of 2
3780 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3781 LHSCst->getValue().isPowerOf2()) {
3782 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3783 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003784 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003785 }
3786
3787 // From here on, we only handle:
3788 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3789 if (Val != Val2) return 0;
3790
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003791 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3792 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3793 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3794 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3795 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3796 return 0;
3797
3798 // We can't fold (ugt x, C) & (sgt x, C2).
3799 if (!PredicatesFoldable(LHSCC, RHSCC))
3800 return 0;
3801
3802 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003803 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 if (ICmpInst::isSignedPredicate(LHSCC) ||
3805 (ICmpInst::isEquality(LHSCC) &&
3806 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003807 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003808 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003809 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3810
3811 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003812 std::swap(LHS, RHS);
3813 std::swap(LHSCst, RHSCst);
3814 std::swap(LHSCC, RHSCC);
3815 }
3816
3817 // At this point, we know we have have two icmp instructions
3818 // comparing a value against two constants and and'ing the result
3819 // together. Because of the above check, we know that we only have
3820 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3821 // (from the FoldICmpLogical check above), that the two constants
3822 // are not equal and that the larger constant is on the RHS
3823 assert(LHSCst != RHSCst && "Compares not folded above?");
3824
3825 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003826 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003827 case ICmpInst::ICMP_EQ:
3828 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003829 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003830 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3831 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3832 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003833 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003834 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3835 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3836 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3837 return ReplaceInstUsesWith(I, LHS);
3838 }
3839 case ICmpInst::ICMP_NE:
3840 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003841 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003842 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003843 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003844 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003845 break; // (X != 13 & X u< 15) -> no change
3846 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003847 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003848 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003849 break; // (X != 13 & X s< 15) -> no change
3850 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3851 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3852 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3853 return ReplaceInstUsesWith(I, RHS);
3854 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003855 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3856 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003857 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3858 Val->getName()+".off");
3859 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003860 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003861 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 }
3863 break; // (X != 13 & X != 15) -> no change
3864 }
3865 break;
3866 case ICmpInst::ICMP_ULT:
3867 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003868 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003869 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3870 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003871 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003872 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3873 break;
3874 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3875 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3876 return ReplaceInstUsesWith(I, LHS);
3877 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3878 break;
3879 }
3880 break;
3881 case ICmpInst::ICMP_SLT:
3882 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003883 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003884 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3885 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003886 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003887 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3888 break;
3889 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3890 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3891 return ReplaceInstUsesWith(I, LHS);
3892 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3893 break;
3894 }
3895 break;
3896 case ICmpInst::ICMP_UGT:
3897 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003898 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003899 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3900 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3901 return ReplaceInstUsesWith(I, RHS);
3902 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3903 break;
3904 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003905 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003906 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003907 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003908 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003909 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3910 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003911 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3912 break;
3913 }
3914 break;
3915 case ICmpInst::ICMP_SGT:
3916 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003917 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003918 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3919 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3920 return ReplaceInstUsesWith(I, RHS);
3921 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3922 break;
3923 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003924 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003925 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003926 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003927 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003928 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3929 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3931 break;
3932 }
3933 break;
3934 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003935
3936 return 0;
3937}
3938
Chris Lattner42d1be02009-07-23 05:14:02 +00003939Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3940 FCmpInst *RHS) {
3941
3942 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3943 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3944 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3945 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3946 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3947 // If either of the constants are nans, then the whole thing returns
3948 // false.
3949 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3950 return ReplaceInstUsesWith(I, Context->getFalse());
3951 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3952 LHS->getOperand(0), RHS->getOperand(0));
3953 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003954
3955 // Handle vector zeros. This occurs because the canonical form of
3956 // "fcmp ord x,x" is "fcmp ord x, 0".
3957 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3958 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3959 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3960 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003961 return 0;
3962 }
3963
3964 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3965 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3966 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3967
3968
3969 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3970 // Swap RHS operands to match LHS.
3971 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3972 std::swap(Op1LHS, Op1RHS);
3973 }
3974
3975 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3976 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3977 if (Op0CC == Op1CC)
3978 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3979
3980 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3981 return ReplaceInstUsesWith(I, Context->getFalse());
3982 if (Op0CC == FCmpInst::FCMP_TRUE)
3983 return ReplaceInstUsesWith(I, RHS);
3984 if (Op1CC == FCmpInst::FCMP_TRUE)
3985 return ReplaceInstUsesWith(I, LHS);
3986
3987 bool Op0Ordered;
3988 bool Op1Ordered;
3989 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3990 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3991 if (Op1Pred == 0) {
3992 std::swap(LHS, RHS);
3993 std::swap(Op0Pred, Op1Pred);
3994 std::swap(Op0Ordered, Op1Ordered);
3995 }
3996 if (Op0Pred == 0) {
3997 // uno && ueq -> uno && (uno || eq) -> ueq
3998 // ord && olt -> ord && (ord && lt) -> olt
3999 if (Op0Ordered == Op1Ordered)
4000 return ReplaceInstUsesWith(I, RHS);
4001
4002 // uno && oeq -> uno && (ord && eq) -> false
4003 // uno && ord -> false
4004 if (!Op0Ordered)
4005 return ReplaceInstUsesWith(I, Context->getFalse());
4006 // ord && ueq -> ord && (uno || eq) -> oeq
4007 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4008 Op0LHS, Op0RHS, Context));
4009 }
4010 }
4011
4012 return 0;
4013}
4014
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004015
Chris Lattner7e708292002-06-25 16:13:24 +00004016Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004017 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004018 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004019
Chris Lattnere87597f2004-10-16 18:11:37 +00004020 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004021 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004022
Chris Lattner6e7ba452005-01-01 16:22:27 +00004023 // and X, X = X
4024 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004025 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004026
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004027 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004028 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004029 if (SimplifyDemandedInstructionBits(I))
4030 return &I;
4031 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004032 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004033 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004034 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004035 } else if (isa<ConstantAggregateZero>(Op1)) {
4036 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004037 }
4038 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004039
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004040 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004041 const APInt& AndRHSMask = AndRHS->getValue();
4042 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004043
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004044 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004045 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004046 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004047 Value *Op0LHS = Op0I->getOperand(0);
4048 Value *Op0RHS = Op0I->getOperand(1);
4049 switch (Op0I->getOpcode()) {
4050 case Instruction::Xor:
4051 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004052 // If the mask is only needed on one incoming arm, push it up.
4053 if (Op0I->hasOneUse()) {
4054 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4055 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004056 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004057 Op0RHS->getName()+".masked");
4058 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004059 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004060 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004061 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004062 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004063 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4064 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004065 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004066 Op0LHS->getName()+".masked");
4067 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004068 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004069 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4070 }
4071 }
4072
Chris Lattner6e7ba452005-01-01 16:22:27 +00004073 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004074 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004075 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4076 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4077 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4078 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004080 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004081 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004082 break;
4083
4084 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004085 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4086 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4087 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4088 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004090
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004091 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4092 // has 1's for all bits that the subtraction with A might affect.
4093 if (Op0I->hasOneUse()) {
4094 uint32_t BitWidth = AndRHSMask.getBitWidth();
4095 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4096 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4097
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004098 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004099 if (!(A && A->isZero()) && // avoid infinite recursion.
4100 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004101 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004102 InsertNewInstBefore(NewNeg, I);
4103 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4104 }
4105 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004106 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004107
4108 case Instruction::Shl:
4109 case Instruction::LShr:
4110 // (1 << x) & 1 --> zext(x == 0)
4111 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004112 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004113 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4114 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004115 InsertNewInstBefore(NewICmp, I);
4116 return new ZExtInst(NewICmp, I.getType());
4117 }
4118 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004119 }
4120
Chris Lattner58403262003-07-23 19:25:52 +00004121 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004122 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004123 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004124 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004125 // If this is an integer truncation or change from signed-to-unsigned, and
4126 // if the source is an and/or with immediate, transform it. This
4127 // frequently occurs for bitfield accesses.
4128 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004129 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004130 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004131 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004132 if (CastOp->getOpcode() == Instruction::And) {
4133 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004134 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4135 // This will fold the two constants together, which may allow
4136 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004137 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004138 CastOp->getOperand(0), I.getType(),
4139 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004140 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004141 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004142 Constant *C3 =
4143 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4144 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004145 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004146 } else if (CastOp->getOpcode() == Instruction::Or) {
4147 // Change: and (cast (or X, C1) to T), C2
4148 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004149 Constant *C3 =
4150 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4151 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4152 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004153 return ReplaceInstUsesWith(I, AndRHS);
4154 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004155 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004156 }
Chris Lattner06782f82003-07-23 19:36:21 +00004157 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004158
4159 // Try to fold constant and into select arguments.
4160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004162 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004163 if (isa<PHINode>(Op0))
4164 if (Instruction *NV = FoldOpIntoPhi(I))
4165 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004166 }
4167
Owen Andersond672ecb2009-07-03 00:17:18 +00004168 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4169 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004170
Chris Lattner5b62aa72004-06-18 06:07:51 +00004171 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004172 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004173
Misha Brukmancb6267b2004-07-30 12:50:08 +00004174 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004175 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004177 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004178 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004179 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004180 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004181
4182 {
Chris Lattner003b6202007-06-15 05:58:24 +00004183 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004184 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004185 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4186 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004187
4188 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004189 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004190 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004191 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004192 }
4193 }
4194
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004195 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004196 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4197 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004198
4199 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004200 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004201 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004202 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004203 }
4204 }
Chris Lattner64daab52006-04-01 08:03:55 +00004205
4206 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004207 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004208 if (A == Op1) { // (A^B)&A -> A&(A^B)
4209 I.swapOperands(); // Simplify below
4210 std::swap(Op0, Op1);
4211 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4212 cast<BinaryOperator>(Op0)->swapOperands();
4213 I.swapOperands(); // Simplify below
4214 std::swap(Op0, Op1);
4215 }
4216 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004217
Chris Lattner64daab52006-04-01 08:03:55 +00004218 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004219 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004220 if (B == Op0) { // B&(A^B) -> B&(B^A)
4221 cast<BinaryOperator>(Op1)->swapOperands();
4222 std::swap(A, B);
4223 }
4224 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004225 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004226 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004227 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004228 }
4229 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004230
4231 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004232 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4233 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004234 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004235 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4236 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004237 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004238 }
4239
Reid Spencere4d87aa2006-12-23 06:05:41 +00004240 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4241 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004242 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004243 return R;
4244
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004245 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4246 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4247 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004248 }
4249
Chris Lattner6fc205f2006-05-05 06:39:07 +00004250 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004251 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4252 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4253 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4254 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004255 if (SrcTy == Op1C->getOperand(0)->getType() &&
4256 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004257 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004258 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4259 I.getType(), TD) &&
4260 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4261 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004262 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004263 Op1C->getOperand(0),
4264 I.getName());
4265 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004266 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004267 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004268 }
Chris Lattnere511b742006-11-14 07:46:50 +00004269
4270 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004271 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4272 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4273 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004274 SI0->getOperand(1) == SI1->getOperand(1) &&
4275 (SI0->hasOneUse() || SI1->hasOneUse())) {
4276 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004277 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004278 SI1->getOperand(0),
4279 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004280 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004281 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004282 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004283 }
4284
Evan Cheng8db90722008-10-14 17:15:11 +00004285 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004286 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004287 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4288 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4289 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004290 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004291
Chris Lattner7e708292002-06-25 16:13:24 +00004292 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004293}
4294
Chris Lattner8c34cd22008-10-05 02:13:19 +00004295/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4296/// capable of providing pieces of a bswap. The subexpression provides pieces
4297/// of a bswap if it is proven that each of the non-zero bytes in the output of
4298/// the expression came from the corresponding "byte swapped" byte in some other
4299/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4300/// we know that the expression deposits the low byte of %X into the high byte
4301/// of the bswap result and that all other bytes are zero. This expression is
4302/// accepted, the high byte of ByteValues is set to X to indicate a correct
4303/// match.
4304///
4305/// This function returns true if the match was unsuccessful and false if so.
4306/// On entry to the function the "OverallLeftShift" is a signed integer value
4307/// indicating the number of bytes that the subexpression is later shifted. For
4308/// example, if the expression is later right shifted by 16 bits, the
4309/// OverallLeftShift value would be -2 on entry. This is used to specify which
4310/// byte of ByteValues is actually being set.
4311///
4312/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4313/// byte is masked to zero by a user. For example, in (X & 255), X will be
4314/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4315/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4316/// always in the local (OverallLeftShift) coordinate space.
4317///
4318static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4319 SmallVector<Value*, 8> &ByteValues) {
4320 if (Instruction *I = dyn_cast<Instruction>(V)) {
4321 // If this is an or instruction, it may be an inner node of the bswap.
4322 if (I->getOpcode() == Instruction::Or) {
4323 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4324 ByteValues) ||
4325 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4326 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004327 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004328
4329 // If this is a logical shift by a constant multiple of 8, recurse with
4330 // OverallLeftShift and ByteMask adjusted.
4331 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4332 unsigned ShAmt =
4333 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4334 // Ensure the shift amount is defined and of a byte value.
4335 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4336 return true;
4337
4338 unsigned ByteShift = ShAmt >> 3;
4339 if (I->getOpcode() == Instruction::Shl) {
4340 // X << 2 -> collect(X, +2)
4341 OverallLeftShift += ByteShift;
4342 ByteMask >>= ByteShift;
4343 } else {
4344 // X >>u 2 -> collect(X, -2)
4345 OverallLeftShift -= ByteShift;
4346 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004347 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004348 }
4349
4350 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4351 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4352
4353 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4354 ByteValues);
4355 }
4356
4357 // If this is a logical 'and' with a mask that clears bytes, clear the
4358 // corresponding bytes in ByteMask.
4359 if (I->getOpcode() == Instruction::And &&
4360 isa<ConstantInt>(I->getOperand(1))) {
4361 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4362 unsigned NumBytes = ByteValues.size();
4363 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4364 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4365
4366 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4367 // If this byte is masked out by a later operation, we don't care what
4368 // the and mask is.
4369 if ((ByteMask & (1 << i)) == 0)
4370 continue;
4371
4372 // If the AndMask is all zeros for this byte, clear the bit.
4373 APInt MaskB = AndMask & Byte;
4374 if (MaskB == 0) {
4375 ByteMask &= ~(1U << i);
4376 continue;
4377 }
4378
4379 // If the AndMask is not all ones for this byte, it's not a bytezap.
4380 if (MaskB != Byte)
4381 return true;
4382
4383 // Otherwise, this byte is kept.
4384 }
4385
4386 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4387 ByteValues);
4388 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004389 }
4390
Chris Lattner8c34cd22008-10-05 02:13:19 +00004391 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4392 // the input value to the bswap. Some observations: 1) if more than one byte
4393 // is demanded from this input, then it could not be successfully assembled
4394 // into a byteswap. At least one of the two bytes would not be aligned with
4395 // their ultimate destination.
4396 if (!isPowerOf2_32(ByteMask)) return true;
4397 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004398
Chris Lattner8c34cd22008-10-05 02:13:19 +00004399 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4400 // is demanded, it needs to go into byte 0 of the result. This means that the
4401 // byte needs to be shifted until it lands in the right byte bucket. The
4402 // shift amount depends on the position: if the byte is coming from the high
4403 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4404 // low part, it must be shifted left.
4405 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4406 if (InputByteNo < ByteValues.size()/2) {
4407 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4408 return true;
4409 } else {
4410 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411 return true;
4412 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004413
4414 // If the destination byte value is already defined, the values are or'd
4415 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004416 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004418 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004419 return false;
4420}
4421
4422/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4423/// If so, insert the new bswap intrinsic and return it.
4424Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004425 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004426 if (!ITy || ITy->getBitWidth() % 16 ||
4427 // ByteMask only allows up to 32-byte values.
4428 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004429 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430
4431 /// ByteValues - For each byte of the result, we keep track of which value
4432 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004433 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004434 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004435
4436 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004437 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4438 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439 return 0;
4440
4441 // Check to see if all of the bytes come from the same value.
4442 Value *V = ByteValues[0];
4443 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4444
4445 // Check to make sure that all of the bytes come from the same value.
4446 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4447 if (ByteValues[i] != V)
4448 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004449 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004450 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004451 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004452 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004453}
4454
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004455/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4456/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4457/// we can simplify this expression to "cond ? C : D or B".
4458static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004459 Value *C, Value *D,
4460 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004461 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004462 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004463 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004464 return 0;
4465
Chris Lattnera6a474d2008-11-16 04:26:55 +00004466 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004467 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004468 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004469 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004470 return SelectInst::Create(Cond, C, B);
4471 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004472 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004473 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004474 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004475 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004476 return 0;
4477}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004478
Chris Lattner69d4ced2008-11-16 05:20:07 +00004479/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4480Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4481 ICmpInst *LHS, ICmpInst *RHS) {
4482 Value *Val, *Val2;
4483 ConstantInt *LHSCst, *RHSCst;
4484 ICmpInst::Predicate LHSCC, RHSCC;
4485
4486 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004487 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4488 m_ConstantInt(LHSCst)), *Context) ||
4489 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4490 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004491 return 0;
4492
4493 // From here on, we only handle:
4494 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4495 if (Val != Val2) return 0;
4496
4497 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4498 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4499 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4500 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4501 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4502 return 0;
4503
4504 // We can't fold (ugt x, C) | (sgt x, C2).
4505 if (!PredicatesFoldable(LHSCC, RHSCC))
4506 return 0;
4507
4508 // Ensure that the larger constant is on the RHS.
4509 bool ShouldSwap;
4510 if (ICmpInst::isSignedPredicate(LHSCC) ||
4511 (ICmpInst::isEquality(LHSCC) &&
4512 ICmpInst::isSignedPredicate(RHSCC)))
4513 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4514 else
4515 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4516
4517 if (ShouldSwap) {
4518 std::swap(LHS, RHS);
4519 std::swap(LHSCst, RHSCst);
4520 std::swap(LHSCC, RHSCC);
4521 }
4522
4523 // At this point, we know we have have two icmp instructions
4524 // comparing a value against two constants and or'ing the result
4525 // together. Because of the above check, we know that we only have
4526 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4527 // FoldICmpLogical check above), that the two constants are not
4528 // equal.
4529 assert(LHSCst != RHSCst && "Compares not folded above?");
4530
4531 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004532 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004533 case ICmpInst::ICMP_EQ:
4534 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004535 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004536 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004537 if (LHSCst == SubOne(RHSCst, Context)) {
4538 // (X == 13 | X == 14) -> X-13 <u 2
4539 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004540 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4541 Val->getName()+".off");
4542 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004543 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004544 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004545 }
4546 break; // (X == 13 | X == 15) -> no change
4547 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4548 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4549 break;
4550 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4551 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4552 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4553 return ReplaceInstUsesWith(I, RHS);
4554 }
4555 break;
4556 case ICmpInst::ICMP_NE:
4557 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004558 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4560 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4561 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4562 return ReplaceInstUsesWith(I, LHS);
4563 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4564 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4565 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004566 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004567 }
4568 break;
4569 case ICmpInst::ICMP_ULT:
4570 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004571 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004572 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4573 break;
4574 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4575 // If RHSCst is [us]MAXINT, it is always false. Not handling
4576 // this can cause overflow.
4577 if (RHSCst->isMaxValue(false))
4578 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004579 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4580 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004581 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4582 break;
4583 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4584 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4585 return ReplaceInstUsesWith(I, RHS);
4586 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4587 break;
4588 }
4589 break;
4590 case ICmpInst::ICMP_SLT:
4591 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004592 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004593 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4594 break;
4595 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4596 // If RHSCst is [us]MAXINT, it is always false. Not handling
4597 // this can cause overflow.
4598 if (RHSCst->isMaxValue(true))
4599 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004600 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4601 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004602 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4603 break;
4604 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4605 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4606 return ReplaceInstUsesWith(I, RHS);
4607 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4608 break;
4609 }
4610 break;
4611 case ICmpInst::ICMP_UGT:
4612 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004613 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004614 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4615 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4616 return ReplaceInstUsesWith(I, LHS);
4617 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4618 break;
4619 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4620 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004621 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004622 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4623 break;
4624 }
4625 break;
4626 case ICmpInst::ICMP_SGT:
4627 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004628 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004629 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4630 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4631 return ReplaceInstUsesWith(I, LHS);
4632 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4633 break;
4634 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4635 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004636 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004637 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4638 break;
4639 }
4640 break;
4641 }
4642 return 0;
4643}
4644
Chris Lattner5414cc52009-07-23 05:46:22 +00004645Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4646 FCmpInst *RHS) {
4647 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4648 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4649 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4650 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4651 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4652 // If either of the constants are nans, then the whole thing returns
4653 // true.
4654 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4655 return ReplaceInstUsesWith(I, Context->getTrue());
4656
4657 // Otherwise, no need to compare the two constants, compare the
4658 // rest.
4659 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4660 LHS->getOperand(0), RHS->getOperand(0));
4661 }
4662
4663 // Handle vector zeros. This occurs because the canonical form of
4664 // "fcmp uno x,x" is "fcmp uno x, 0".
4665 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4666 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4667 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4668 LHS->getOperand(0), RHS->getOperand(0));
4669
4670 return 0;
4671 }
4672
4673 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4674 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4675 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4676
4677 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4678 // Swap RHS operands to match LHS.
4679 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4680 std::swap(Op1LHS, Op1RHS);
4681 }
4682 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4683 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4684 if (Op0CC == Op1CC)
4685 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4686 Op0LHS, Op0RHS);
4687 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4688 return ReplaceInstUsesWith(I, Context->getTrue());
4689 if (Op0CC == FCmpInst::FCMP_FALSE)
4690 return ReplaceInstUsesWith(I, RHS);
4691 if (Op1CC == FCmpInst::FCMP_FALSE)
4692 return ReplaceInstUsesWith(I, LHS);
4693 bool Op0Ordered;
4694 bool Op1Ordered;
4695 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4696 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4697 if (Op0Ordered == Op1Ordered) {
4698 // If both are ordered or unordered, return a new fcmp with
4699 // or'ed predicates.
4700 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4701 Op0LHS, Op0RHS, Context);
4702 if (Instruction *I = dyn_cast<Instruction>(RV))
4703 return I;
4704 // Otherwise, it's a constant boolean value...
4705 return ReplaceInstUsesWith(I, RV);
4706 }
4707 }
4708 return 0;
4709}
4710
Bill Wendlinga698a472008-12-01 08:23:25 +00004711/// FoldOrWithConstants - This helper function folds:
4712///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004713/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004714///
4715/// into:
4716///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004717/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004718///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004719/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004720Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004721 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004722 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4723 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004724
Bill Wendling286a0542008-12-02 06:24:20 +00004725 Value *V1 = 0;
4726 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004727 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004728
Bill Wendling29976b92008-12-02 06:18:11 +00004729 APInt Xor = CI1->getValue() ^ CI2->getValue();
4730 if (!Xor.isAllOnesValue()) return 0;
4731
Bill Wendling286a0542008-12-02 06:24:20 +00004732 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004733 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004734 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4735 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004736 }
4737
4738 return 0;
4739}
4740
Chris Lattner7e708292002-06-25 16:13:24 +00004741Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004742 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004743 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004744
Chris Lattner42593e62007-03-24 23:56:43 +00004745 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004746 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004747
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004748 // or X, X = X
4749 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004750 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004751
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004752 // See if we can simplify any instructions used by the instruction whose sole
4753 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004754 if (SimplifyDemandedInstructionBits(I))
4755 return &I;
4756 if (isa<VectorType>(I.getType())) {
4757 if (isa<ConstantAggregateZero>(Op1)) {
4758 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4759 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4760 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4761 return ReplaceInstUsesWith(I, I.getOperand(1));
4762 }
Chris Lattner42593e62007-03-24 23:56:43 +00004763 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004764
Chris Lattner3f5b8772002-05-06 16:14:14 +00004765 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004766 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004767 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004768 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004769 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4770 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004771 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004772 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004773 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004774 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004775 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004776 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004777
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004778 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004779 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4780 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004781 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004782 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004783 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004784 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004785 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004786 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004787
4788 // Try to fold constant and into select arguments.
4789 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004791 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004792 if (isa<PHINode>(Op0))
4793 if (Instruction *NV = FoldOpIntoPhi(I))
4794 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004795 }
4796
Chris Lattner4f637d42006-01-06 17:59:59 +00004797 Value *A = 0, *B = 0;
4798 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004799
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004800 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004801 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4802 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004803 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004804 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4805 return ReplaceInstUsesWith(I, Op0);
4806
Chris Lattner6423d4c2006-07-10 20:25:24 +00004807 // (A | B) | C and A | (B | C) -> bswap if possible.
4808 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004809 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4810 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4811 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4812 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004813 if (Instruction *BSwap = MatchBSwap(I))
4814 return BSwap;
4815 }
4816
Chris Lattner6e4c6492005-05-09 04:58:36 +00004817 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004818 if (Op0->hasOneUse() &&
4819 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004820 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004821 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004822 InsertNewInstBefore(NOr, I);
4823 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004824 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004825 }
4826
4827 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004828 if (Op1->hasOneUse() &&
4829 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004830 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004831 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004832 InsertNewInstBefore(NOr, I);
4833 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004834 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004835 }
4836
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004837 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004838 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004839 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4840 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004841 Value *V1 = 0, *V2 = 0, *V3 = 0;
4842 C1 = dyn_cast<ConstantInt>(C);
4843 C2 = dyn_cast<ConstantInt>(D);
4844 if (C1 && C2) { // (A & C1)|(B & C2)
4845 // If we have: ((V + N) & C1) | (V & C2)
4846 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4847 // replace with V+N.
4848 if (C1->getValue() == ~C2->getValue()) {
4849 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004851 // Add commutes, try both ways.
4852 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4853 return ReplaceInstUsesWith(I, A);
4854 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4855 return ReplaceInstUsesWith(I, A);
4856 }
4857 // Or commutes, try both ways.
4858 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004859 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004860 // Add commutes, try both ways.
4861 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4862 return ReplaceInstUsesWith(I, B);
4863 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4864 return ReplaceInstUsesWith(I, B);
4865 }
4866 }
Chris Lattner044e5332007-04-08 08:01:49 +00004867 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004868 }
4869
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004870 // Check to see if we have any common things being and'ed. If so, find the
4871 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004872 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4873 if (A == B) // (A & C)|(A & D) == A & (C|D)
4874 V1 = A, V2 = C, V3 = D;
4875 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4876 V1 = A, V2 = B, V3 = C;
4877 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4878 V1 = C, V2 = A, V3 = D;
4879 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4880 V1 = C, V2 = A, V3 = B;
4881
4882 if (V1) {
4883 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004884 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4885 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004886 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004887 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004888
Dan Gohman1975d032008-10-30 20:40:10 +00004889 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004890 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004891 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004892 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004893 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004894 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004895 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004896 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004897 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004898
Bill Wendlingb01865c2008-11-30 13:52:49 +00004899 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004900 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4901 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004902 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004903 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004904 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4905 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004906 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004907 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004908 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4909 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004910 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004911 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004912 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4913 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004914 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004915 }
Chris Lattnere511b742006-11-14 07:46:50 +00004916
4917 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004918 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4919 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4920 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004921 SI0->getOperand(1) == SI1->getOperand(1) &&
4922 (SI0->hasOneUse() || SI1->hasOneUse())) {
4923 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004924 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004925 SI1->getOperand(0),
4926 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004927 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004928 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004929 }
4930 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004931
Bill Wendlingb3833d12008-12-01 01:07:11 +00004932 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004933 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4934 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004935 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004936 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004937 }
4938 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004939 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4940 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004941 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004942 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004943 }
4944
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004945 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004946 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004947 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004948 } else {
4949 A = 0;
4950 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004951 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004952 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004953 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004954 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004955
Misha Brukmancb6267b2004-07-30 12:50:08 +00004956 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004957 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004958 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004959 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004960 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004961 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004962 }
Chris Lattnera2881962003-02-18 19:28:33 +00004963
Reid Spencere4d87aa2006-12-23 06:05:41 +00004964 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4965 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004966 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004967 return R;
4968
Chris Lattner69d4ced2008-11-16 05:20:07 +00004969 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4970 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4971 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004972 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004973
4974 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004975 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004976 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004977 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004978 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4979 !isa<ICmpInst>(Op1C->getOperand(0))) {
4980 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004981 if (SrcTy == Op1C->getOperand(0)->getType() &&
4982 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004983 // Only do this if the casts both really cause code to be
4984 // generated.
4985 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4986 I.getType(), TD) &&
4987 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4988 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004989 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004990 Op1C->getOperand(0),
4991 I.getName());
4992 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004993 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004994 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004995 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004996 }
Chris Lattner99c65742007-10-24 05:38:08 +00004997 }
4998
4999
5000 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5001 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005002 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5003 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5004 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005005 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005006
Chris Lattner7e708292002-06-25 16:13:24 +00005007 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005008}
5009
Dan Gohman844731a2008-05-13 00:00:25 +00005010namespace {
5011
Chris Lattnerc317d392004-02-16 01:20:27 +00005012// XorSelf - Implements: X ^ X --> 0
5013struct XorSelf {
5014 Value *RHS;
5015 XorSelf(Value *rhs) : RHS(rhs) {}
5016 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5017 Instruction *apply(BinaryOperator &Xor) const {
5018 return &Xor;
5019 }
5020};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005021
Dan Gohman844731a2008-05-13 00:00:25 +00005022}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005023
Chris Lattner7e708292002-06-25 16:13:24 +00005024Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005025 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005027
Evan Chengd34af782008-03-25 20:07:13 +00005028 if (isa<UndefValue>(Op1)) {
5029 if (isa<UndefValue>(Op0))
5030 // Handle undef ^ undef -> 0 special case. This is a common
5031 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005032 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005033 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005034 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005035
Chris Lattnerc317d392004-02-16 01:20:27 +00005036 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005037 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005038 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005039 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005040 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005041
5042 // See if we can simplify any instructions used by the instruction whose sole
5043 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005044 if (SimplifyDemandedInstructionBits(I))
5045 return &I;
5046 if (isa<VectorType>(I.getType()))
5047 if (isa<ConstantAggregateZero>(Op1))
5048 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005049
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005050 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005051 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005052 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5053 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5054 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5055 if (Op0I->getOpcode() == Instruction::And ||
5056 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005057 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5058 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005059 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005060 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005061 Op0I->getOperand(1)->getName()+".not");
5062 InsertNewInstBefore(NotY, I);
5063 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005064 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005065 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005066 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005067 }
5068 }
5069 }
5070 }
5071
5072
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00005074 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005075 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005076 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005077 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005078 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005079
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005080 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005081 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005082 FCI->getOperand(0), FCI->getOperand(1));
5083 }
5084
Nick Lewycky517e1f52008-05-31 19:01:33 +00005085 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5086 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5087 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5088 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5089 Instruction::CastOps Opcode = Op0C->getOpcode();
5090 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005091 if (RHS == Context->getConstantExprCast(Opcode,
Owen Andersonb3056fa2009-07-21 18:03:38 +00005092 Context->getTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005093 Op0C->getDestTy())) {
5094 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005095 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005096 CI->getOpcode(), CI->getInversePredicate(),
5097 CI->getOperand(0), CI->getOperand(1)), I);
5098 NewCI->takeName(CI);
5099 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5100 }
5101 }
5102 }
5103 }
5104 }
5105
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005107 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005108 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5109 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005110 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5111 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005112 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005113 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005114 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005115
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005116 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005117 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005118 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005119 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005120 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005121 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005122 Context->getConstantExprSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005123 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005124 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005125 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005126 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005127 Constant *C = ConstantInt::get(*Context,
5128 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005130
Chris Lattner7c4049c2004-01-12 19:35:11 +00005131 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005132 } else if (Op0I->getOpcode() == Instruction::Or) {
5133 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005134 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005135 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005136 // Anything in both C1 and C2 is known to be zero, remove it from
5137 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005138 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5139 NewRHS = Context->getConstantExprAnd(NewRHS,
5140 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005141 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005142 I.setOperand(0, Op0I->getOperand(0));
5143 I.setOperand(1, NewRHS);
5144 return &I;
5145 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005146 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005147 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005148 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005149
5150 // Try to fold constant and into select arguments.
5151 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005152 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005153 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005154 if (isa<PHINode>(Op0))
5155 if (Instruction *NV = FoldOpIntoPhi(I))
5156 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005157 }
5158
Owen Andersond672ecb2009-07-03 00:17:18 +00005159 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005160 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005161 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005162
Owen Andersond672ecb2009-07-03 00:17:18 +00005163 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005164 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005165 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005166
Chris Lattner318bf792007-03-18 22:51:34 +00005167
5168 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5169 if (Op1I) {
5170 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005171 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005172 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005173 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005174 I.swapOperands();
5175 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005176 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005177 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005178 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005179 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005181 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005182 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005183 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005184 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5185 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005186 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005187 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005188 std::swap(A, B);
5189 }
Chris Lattner318bf792007-03-18 22:51:34 +00005190 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005191 I.swapOperands(); // Simplified below.
5192 std::swap(Op0, Op1);
5193 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005194 }
Chris Lattner318bf792007-03-18 22:51:34 +00005195 }
5196
5197 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5198 if (Op0I) {
5199 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005200 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5201 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005202 if (A == Op1) // (B|A)^B == (A|B)^B
5203 std::swap(A, B);
5204 if (B == Op1) { // (A|B)^B == A & ~B
5205 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005206 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5207 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005208 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005209 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005210 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005211 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005212 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005213 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005214 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5215 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005216 if (A == Op1) // (A&B)^A -> (B&A)^A
5217 std::swap(A, B);
5218 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005219 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005220 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005221 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005222 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005223 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005224 }
Chris Lattner318bf792007-03-18 22:51:34 +00005225 }
5226
5227 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5228 if (Op0I && Op1I && Op0I->isShift() &&
5229 Op0I->getOpcode() == Op1I->getOpcode() &&
5230 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5231 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5232 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005233 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005234 Op1I->getOperand(0),
5235 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005236 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005237 Op1I->getOperand(1));
5238 }
5239
5240 if (Op0I && Op1I) {
5241 Value *A, *B, *C, *D;
5242 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005243 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005245 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005246 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005247 }
5248 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005249 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5250 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005251 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005252 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005253 }
5254
5255 // (A & B)^(C & D)
5256 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005257 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5258 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005259 // (X & Y)^(X & Y) -> (Y^Z) & X
5260 Value *X = 0, *Y = 0, *Z = 0;
5261 if (A == C)
5262 X = A, Y = B, Z = D;
5263 else if (A == D)
5264 X = A, Y = B, Z = C;
5265 else if (B == C)
5266 X = B, Y = A, Z = D;
5267 else if (B == D)
5268 X = B, Y = A, Z = C;
5269
5270 if (X) {
5271 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005272 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5273 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005274 }
5275 }
5276 }
5277
Reid Spencere4d87aa2006-12-23 06:05:41 +00005278 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005280 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005281 return R;
5282
Chris Lattner6fc205f2006-05-05 06:39:07 +00005283 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005284 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005285 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005286 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005289 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5291 I.getType(), TD) &&
5292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5293 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005294 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005295 Op1C->getOperand(0),
5296 I.getName());
5297 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005298 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005299 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005300 }
Chris Lattner99c65742007-10-24 05:38:08 +00005301 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005302
Chris Lattner7e708292002-06-25 16:13:24 +00005303 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005304}
5305
Owen Andersond672ecb2009-07-03 00:17:18 +00005306static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005307 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005308 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005309}
Chris Lattnera96879a2004-09-29 17:40:11 +00005310
Dan Gohman6de29f82009-06-15 22:12:54 +00005311static bool HasAddOverflow(ConstantInt *Result,
5312 ConstantInt *In1, ConstantInt *In2,
5313 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005314 if (IsSigned)
5315 if (In2->getValue().isNegative())
5316 return Result->getValue().sgt(In1->getValue());
5317 else
5318 return Result->getValue().slt(In1->getValue());
5319 else
5320 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005321}
5322
Dan Gohman6de29f82009-06-15 22:12:54 +00005323/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005324/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005325static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005326 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005327 bool IsSigned = false) {
5328 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005329
Dan Gohman6de29f82009-06-15 22:12:54 +00005330 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5331 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005332 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005333 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5334 ExtractElement(In1, Idx, Context),
5335 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005336 IsSigned))
5337 return true;
5338 }
5339 return false;
5340 }
5341
5342 return HasAddOverflow(cast<ConstantInt>(Result),
5343 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5344 IsSigned);
5345}
5346
5347static bool HasSubOverflow(ConstantInt *Result,
5348 ConstantInt *In1, ConstantInt *In2,
5349 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005350 if (IsSigned)
5351 if (In2->getValue().isNegative())
5352 return Result->getValue().slt(In1->getValue());
5353 else
5354 return Result->getValue().sgt(In1->getValue());
5355 else
5356 return Result->getValue().ugt(In1->getValue());
5357}
5358
Dan Gohman6de29f82009-06-15 22:12:54 +00005359/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5360/// overflowed for this type.
5361static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005362 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005363 bool IsSigned = false) {
5364 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005365
5366 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005368 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005369 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5370 ExtractElement(In1, Idx, Context),
5371 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005372 IsSigned))
5373 return true;
5374 }
5375 return false;
5376 }
5377
5378 return HasSubOverflow(cast<ConstantInt>(Result),
5379 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380 IsSigned);
5381}
5382
Chris Lattner574da9b2005-01-13 20:14:25 +00005383/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5384/// code necessary to compute the offset from the base pointer (without adding
5385/// in the base pointer). Return the result as a signed integer of intptr size.
5386static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005387 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005388 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005389 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005390 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005391 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005392
5393 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005394 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005395 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005396
Gabor Greif177dd3f2008-06-12 21:37:33 +00005397 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5398 ++i, ++GTI) {
5399 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005400 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005401 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5402 if (OpC->isZero()) continue;
5403
5404 // Handle a struct index, which adds its field offset to the pointer.
5405 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5407
5408 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005409 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005410 ConstantInt::get(*Context,
5411 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005412 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005414 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005415 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005416 GEP->getName()+".offs"), I);
5417 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005418 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005419
Owen Andersoneed707b2009-07-24 23:12:02 +00005420 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005421 Constant *OC =
5422 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5423 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005424 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005425 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005426 else {
5427 // Emit an add instruction.
5428 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005429 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005430 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005431 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005432 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005433 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005434 // Convert to correct type.
5435 if (Op->getType() != IntPtrTy) {
5436 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005437 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005438 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005439 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5440 true,
5441 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005442 }
5443 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005444 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005445 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005446 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005448 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005449 GEP->getName()+".idx"), I);
5450 }
5451
5452 // Emit an add instruction.
5453 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005454 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005455 cast<Constant>(Result));
5456 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005457 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005458 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005459 }
5460 return Result;
5461}
5462
Chris Lattner10c0d912008-04-22 02:53:33 +00005463
Dan Gohman8f080f02009-07-17 22:16:21 +00005464/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5465/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5466/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5467/// be complex, and scales are involved. The above expression would also be
5468/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5469/// This later form is less amenable to optimization though, and we are allowed
5470/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005471///
5472/// If we can't emit an optimized form for this expression, this returns null.
5473///
5474static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5475 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005476 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005477 gep_type_iterator GTI = gep_type_begin(GEP);
5478
5479 // Check to see if this gep only has a single variable index. If so, and if
5480 // any constant indices are a multiple of its scale, then we can compute this
5481 // in terms of the scale of the variable index. For example, if the GEP
5482 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5483 // because the expression will cross zero at the same point.
5484 unsigned i, e = GEP->getNumOperands();
5485 int64_t Offset = 0;
5486 for (i = 1; i != e; ++i, ++GTI) {
5487 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5488 // Compute the aggregate offset of constant indices.
5489 if (CI->isZero()) continue;
5490
5491 // Handle a struct index, which adds its field offset to the pointer.
5492 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5493 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5494 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005495 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005496 Offset += Size*CI->getSExtValue();
5497 }
5498 } else {
5499 // Found our variable index.
5500 break;
5501 }
5502 }
5503
5504 // If there are no variable indices, we must have a constant offset, just
5505 // evaluate it the general way.
5506 if (i == e) return 0;
5507
5508 Value *VariableIdx = GEP->getOperand(i);
5509 // Determine the scale factor of the variable element. For example, this is
5510 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005511 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005512
5513 // Verify that there are no other variable indices. If so, emit the hard way.
5514 for (++i, ++GTI; i != e; ++i, ++GTI) {
5515 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5516 if (!CI) return 0;
5517
5518 // Compute the aggregate offset of constant indices.
5519 if (CI->isZero()) continue;
5520
5521 // Handle a struct index, which adds its field offset to the pointer.
5522 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5523 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5524 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005525 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005526 Offset += Size*CI->getSExtValue();
5527 }
5528 }
5529
5530 // Okay, we know we have a single variable index, which must be a
5531 // pointer/array/vector index. If there is no offset, life is simple, return
5532 // the index.
5533 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5534 if (Offset == 0) {
5535 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5536 // we don't need to bother extending: the extension won't affect where the
5537 // computation crosses zero.
5538 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5539 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005540 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005541 return VariableIdx;
5542 }
5543
5544 // Otherwise, there is an index. The computation we will do will be modulo
5545 // the pointer size, so get it.
5546 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5547
5548 Offset &= PtrSizeMask;
5549 VariableScale &= PtrSizeMask;
5550
5551 // To do this transformation, any constant index must be a multiple of the
5552 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5553 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5554 // multiple of the variable scale.
5555 int64_t NewOffs = Offset / (int64_t)VariableScale;
5556 if (Offset != NewOffs*(int64_t)VariableScale)
5557 return 0;
5558
5559 // Okay, we can do this evaluation. Start by converting the index to intptr.
5560 const Type *IntPtrTy = TD.getIntPtrType();
5561 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005562 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005563 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005564 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005565 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005566 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005567}
5568
5569
Reid Spencere4d87aa2006-12-23 06:05:41 +00005570/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005571/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005572Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5573 ICmpInst::Predicate Cond,
5574 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005575 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005576
Chris Lattner10c0d912008-04-22 02:53:33 +00005577 // Look through bitcasts.
5578 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5579 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005580
Chris Lattner574da9b2005-01-13 20:14:25 +00005581 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005582 if (TD && PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005583 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005584 // This transformation (ignoring the base and scales) is valid because we
5585 // know pointers can't overflow. See if we can output an optimized form.
5586 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5587
5588 // If not, synthesize the offset the hard way.
5589 if (Offset == 0)
5590 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005591 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005592 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005593 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005594 // If the base pointers are different, but the indices are the same, just
5595 // compare the base pointer.
5596 if (PtrBase != GEPRHS->getOperand(0)) {
5597 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005598 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005599 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005600 if (IndicesTheSame)
5601 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5602 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5603 IndicesTheSame = false;
5604 break;
5605 }
5606
5607 // If all indices are the same, just compare the base pointers.
5608 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005609 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005610 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005611
5612 // Otherwise, the base pointers are different and the indices are
5613 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005614 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005615 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005616
Chris Lattnere9d782b2005-01-13 22:25:21 +00005617 // If one of the GEPs has all zero indices, recurse.
5618 bool AllZeros = true;
5619 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5620 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5621 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5622 AllZeros = false;
5623 break;
5624 }
5625 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005626 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5627 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005628
5629 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005630 AllZeros = true;
5631 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5632 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5633 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5634 AllZeros = false;
5635 break;
5636 }
5637 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005638 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005639
Chris Lattner4401c9c2005-01-14 00:20:05 +00005640 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5641 // If the GEPs only differ by one index, compare it.
5642 unsigned NumDifferences = 0; // Keep track of # differences.
5643 unsigned DiffOperand = 0; // The operand that differs.
5644 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5645 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005646 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5647 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005648 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005649 NumDifferences = 2;
5650 break;
5651 } else {
5652 if (NumDifferences++) break;
5653 DiffOperand = i;
5654 }
5655 }
5656
5657 if (NumDifferences == 0) // SAME GEP?
5658 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneed707b2009-07-24 23:12:02 +00005659 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005660 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005661
Chris Lattner4401c9c2005-01-14 00:20:05 +00005662 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005663 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5664 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005665 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005666 return new ICmpInst(*Context,
5667 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005668 }
5669 }
5670
Reid Spencere4d87aa2006-12-23 06:05:41 +00005671 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005672 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005673 if (TD &&
5674 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005675 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5676 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5677 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5678 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005679 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005680 }
5681 }
5682 return 0;
5683}
5684
Chris Lattnera5406232008-05-19 20:18:56 +00005685/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5686///
5687Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5688 Instruction *LHSI,
5689 Constant *RHSC) {
5690 if (!isa<ConstantFP>(RHSC)) return 0;
5691 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5692
5693 // Get the width of the mantissa. We don't want to hack on conversions that
5694 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005695 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005696 if (MantissaWidth == -1) return 0; // Unknown.
5697
5698 // Check to see that the input is converted from an integer type that is small
5699 // enough that preserves all bits. TODO: check here for "known" sign bits.
5700 // 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 +00005701 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005702
5703 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005704 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5705 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005706 ++InputSize;
5707
5708 // If the conversion would lose info, don't hack on this.
5709 if ((int)InputSize > MantissaWidth)
5710 return 0;
5711
5712 // Otherwise, we can potentially simplify the comparison. We know that it
5713 // will always come through as an integer value and we know the constant is
5714 // not a NAN (it would have been previously simplified).
5715 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5716
5717 ICmpInst::Predicate Pred;
5718 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005719 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OEQ:
5722 Pred = ICmpInst::ICMP_EQ;
5723 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OGT:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5727 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_OGE:
5730 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 case FCmpInst::FCMP_OLT:
5734 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5735 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005736 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005737 case FCmpInst::FCMP_OLE:
5738 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5739 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005741 case FCmpInst::FCMP_ONE:
5742 Pred = ICmpInst::ICMP_NE;
5743 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005744 case FCmpInst::FCMP_ORD:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005745 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005746 case FCmpInst::FCMP_UNO:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005747 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005748 }
5749
5750 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5751
5752 // Now we know that the APFloat is a normal number, zero or inf.
5753
Chris Lattner85162782008-05-20 03:50:52 +00005754 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005755 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005756 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005757
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005758 if (!LHSUnsigned) {
5759 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5760 // and large values.
5761 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5762 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5763 APFloat::rmNearestTiesToEven);
5764 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5765 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5766 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005767 return ReplaceInstUsesWith(I, Context->getTrue());
5768 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005769 }
5770 } else {
5771 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5772 // +INF and large values.
5773 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5774 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5775 APFloat::rmNearestTiesToEven);
5776 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5777 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5778 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005779 return ReplaceInstUsesWith(I, Context->getTrue());
5780 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005781 }
Chris Lattnera5406232008-05-19 20:18:56 +00005782 }
5783
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005784 if (!LHSUnsigned) {
5785 // See if the RHS value is < SignedMin.
5786 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5787 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5788 APFloat::rmNearestTiesToEven);
5789 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5790 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5791 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005792 return ReplaceInstUsesWith(I, Context->getTrue());
5793 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005794 }
Chris Lattnera5406232008-05-19 20:18:56 +00005795 }
5796
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005797 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5798 // [0, UMAX], but it may still be fractional. See if it is fractional by
5799 // casting the FP value to the integer value and back, checking for equality.
5800 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005801 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005802 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5803 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005804 if (!RHS.isZero()) {
5805 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005806 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5807 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005808 if (!Equal) {
5809 // If we had a comparison against a fractional value, we have to adjust
5810 // the compare predicate and sometimes the value. RHSC is rounded towards
5811 // zero at this point.
5812 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005813 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005814 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00005815 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005816 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00005817 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005818 case ICmpInst::ICMP_ULE:
5819 // (float)int <= 4.4 --> int <= 4
5820 // (float)int <= -4.4 --> false
5821 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005822 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005823 break;
5824 case ICmpInst::ICMP_SLE:
5825 // (float)int <= 4.4 --> int <= 4
5826 // (float)int <= -4.4 --> int < -4
5827 if (RHS.isNegative())
5828 Pred = ICmpInst::ICMP_SLT;
5829 break;
5830 case ICmpInst::ICMP_ULT:
5831 // (float)int < -4.4 --> false
5832 // (float)int < 4.4 --> int <= 4
5833 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005834 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005835 Pred = ICmpInst::ICMP_ULE;
5836 break;
5837 case ICmpInst::ICMP_SLT:
5838 // (float)int < -4.4 --> int < -4
5839 // (float)int < 4.4 --> int <= 4
5840 if (!RHS.isNegative())
5841 Pred = ICmpInst::ICMP_SLE;
5842 break;
5843 case ICmpInst::ICMP_UGT:
5844 // (float)int > 4.4 --> int > 4
5845 // (float)int > -4.4 --> true
5846 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005847 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005848 break;
5849 case ICmpInst::ICMP_SGT:
5850 // (float)int > 4.4 --> int > 4
5851 // (float)int > -4.4 --> int >= -4
5852 if (RHS.isNegative())
5853 Pred = ICmpInst::ICMP_SGE;
5854 break;
5855 case ICmpInst::ICMP_UGE:
5856 // (float)int >= -4.4 --> true
5857 // (float)int >= 4.4 --> int > 4
5858 if (!RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005859 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005860 Pred = ICmpInst::ICMP_UGT;
5861 break;
5862 case ICmpInst::ICMP_SGE:
5863 // (float)int >= -4.4 --> int >= -4
5864 // (float)int >= 4.4 --> int > 4
5865 if (!RHS.isNegative())
5866 Pred = ICmpInst::ICMP_SGT;
5867 break;
5868 }
Chris Lattnera5406232008-05-19 20:18:56 +00005869 }
5870 }
5871
5872 // Lower this FP comparison into an appropriate integer version of the
5873 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005874 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005875}
5876
Reid Spencere4d87aa2006-12-23 06:05:41 +00005877Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5878 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005879 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005880
Chris Lattner58e97462007-01-14 19:42:17 +00005881 // Fold trivial predicates.
5882 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005883 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005884 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005885 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005886
5887 // Simplify 'fcmp pred X, X'
5888 if (Op0 == Op1) {
5889 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005890 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005891 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5892 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5893 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005894 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005895 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5896 case FCmpInst::FCMP_OLT: // True if ordered and less than
5897 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005898 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005899
5900 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5901 case FCmpInst::FCMP_ULT: // True if unordered or less than
5902 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5903 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5904 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5905 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005906 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005907 return &I;
5908
5909 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5910 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5911 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5912 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5913 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5914 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005915 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005916 return &I;
5917 }
5918 }
5919
Reid Spencere4d87aa2006-12-23 06:05:41 +00005920 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005921 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005922
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 // Handle fcmp with constant RHS
5924 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005925 // If the constant is a nan, see if we can fold the comparison based on it.
5926 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5927 if (CFP->getValueAPF().isNaN()) {
5928 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb3056fa2009-07-21 18:03:38 +00005929 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005930 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5931 "Comparison must be either ordered or unordered!");
5932 // True if unordered.
Owen Andersonb3056fa2009-07-21 18:03:38 +00005933 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005934 }
5935 }
5936
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5938 switch (LHSI->getOpcode()) {
5939 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005940 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5941 // block. If in the same block, we're encouraging jump threading. If
5942 // not, we are just pessimizing the code by making an i1 phi.
5943 if (LHSI->getParent() == I.getParent())
5944 if (Instruction *NV = FoldOpIntoPhi(I))
5945 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005947 case Instruction::SIToFP:
5948 case Instruction::UIToFP:
5949 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5950 return NV;
5951 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005952 case Instruction::Select:
5953 // If either operand of the select is a constant, we can fold the
5954 // comparison into the select arms, which will cause one to be
5955 // constant folded and the select turned into a bitwise or.
5956 Value *Op1 = 0, *Op2 = 0;
5957 if (LHSI->hasOneUse()) {
5958 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5959 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005960 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005962 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005963 LHSI->getOperand(2), RHSC,
5964 I.getName()), I);
5965 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5966 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005967 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005968 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005969 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005970 LHSI->getOperand(1), RHSC,
5971 I.getName()), I);
5972 }
5973 }
5974
5975 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005976 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 break;
5978 }
5979 }
5980
5981 return Changed ? &I : 0;
5982}
5983
5984Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5985 bool Changed = SimplifyCompare(I);
5986 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5987 const Type *Ty = Op0->getType();
5988
5989 // icmp X, X
5990 if (Op0 == Op1)
Owen Andersoneed707b2009-07-24 23:12:02 +00005991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005992 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005993
5994 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005995 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005996
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005998 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005999 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6000 isa<ConstantPointerNull>(Op0)) &&
6001 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006002 isa<ConstantPointerNull>(Op1)))
Owen Andersoneed707b2009-07-24 23:12:02 +00006003 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006004 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006005
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006007 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006008 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006009 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006010 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006011 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006012 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006013 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006014 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006015 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006016 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006017
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006019 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006020 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006022 Instruction *Not = BinaryOperator::CreateNot(*Context,
6023 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006024 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006025 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006026 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 case ICmpInst::ICMP_SGT:
6028 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006029 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006031 Instruction *Not = BinaryOperator::CreateNot(*Context,
6032 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006033 InsertNewInstBefore(Not, I);
6034 return BinaryOperator::CreateAnd(Not, Op0);
6035 }
6036 case ICmpInst::ICMP_UGE:
6037 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6038 // FALL THROUGH
6039 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006040 Instruction *Not = BinaryOperator::CreateNot(*Context,
6041 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006042 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006043 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006044 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006045 case ICmpInst::ICMP_SGE:
6046 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6047 // FALL THROUGH
6048 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006049 Instruction *Not = BinaryOperator::CreateNot(*Context,
6050 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006051 InsertNewInstBefore(Not, I);
6052 return BinaryOperator::CreateOr(Not, Op0);
6053 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006054 }
Chris Lattner8b170942002-08-09 23:47:40 +00006055 }
6056
Dan Gohman1c8491e2009-04-25 17:12:48 +00006057 unsigned BitWidth = 0;
6058 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006059 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6060 else if (Ty->isIntOrIntVector())
6061 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006062
6063 bool isSignBit = false;
6064
Dan Gohman81b28ce2008-09-16 18:46:06 +00006065 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006066 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006067 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006068
Chris Lattnerb6566012008-01-05 01:18:20 +00006069 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6070 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006071 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006072 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006073 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006074 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006075
Dan Gohman81b28ce2008-09-16 18:46:06 +00006076 // If we have an icmp le or icmp ge instruction, turn it into the
6077 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6078 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006079 switch (I.getPredicate()) {
6080 default: break;
6081 case ICmpInst::ICMP_ULE:
6082 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006083 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006084 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6085 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006086 case ICmpInst::ICMP_SLE:
6087 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006088 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006089 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6090 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006091 case ICmpInst::ICMP_UGE:
6092 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006093 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006094 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6095 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006096 case ICmpInst::ICMP_SGE:
6097 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006098 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006099 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6100 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006101 }
6102
Chris Lattner183661e2008-07-11 05:40:05 +00006103 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006104 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006105 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6107 }
6108
6109 // See if we can fold the comparison based on range information we can get
6110 // by checking whether bits are known to be zero or one in the input.
6111 if (BitWidth != 0) {
6112 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6113 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6114
6115 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006116 isSignBit ? APInt::getSignBit(BitWidth)
6117 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006119 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 if (SimplifyDemandedBits(I.getOperandUse(1),
6121 APInt::getAllOnesValue(BitWidth),
6122 Op1KnownZero, Op1KnownOne, 0))
6123 return &I;
6124
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006125 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006126 // in. Compute the Min, Max and RHS values based on the known bits. For the
6127 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6129 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6130 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6131 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6132 Op0Min, Op0Max);
6133 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6134 Op1Min, Op1Max);
6135 } else {
6136 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6137 Op0Min, Op0Max);
6138 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6139 Op1Min, Op1Max);
6140 }
6141
Chris Lattner183661e2008-07-11 05:40:05 +00006142 // If Min and Max are known to be the same, then SimplifyDemandedBits
6143 // figured out that the LHS is a constant. Just constant fold this now so
6144 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006146 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006147 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006149 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006150 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151
Chris Lattner183661e2008-07-11 05:40:05 +00006152 // Based on the range information we know about the LHS, see if we can
6153 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006155 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006156 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006158 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006159 break;
6160 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006162 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006163 break;
6164 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006166 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006168 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006170 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6172 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6174 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006175
6176 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6177 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006178 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006179 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 }
Chris Lattner84dff672008-07-11 05:08:55 +00006181 break;
6182 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006184 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006186 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187
6188 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006189 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6191 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006192 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6193 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194
6195 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6196 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006197 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006198 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 }
Chris Lattner84dff672008-07-11 05:08:55 +00006200 break;
6201 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006203 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006205 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006207 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6209 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006210 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6211 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 }
Chris Lattner84dff672008-07-11 05:08:55 +00006213 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 case ICmpInst::ICMP_SGT:
6215 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006216 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006218 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219
6220 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006221 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006224 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6225 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 }
6227 break;
6228 case ICmpInst::ICMP_SGE:
6229 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6230 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006231 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006232 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006233 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006234 break;
6235 case ICmpInst::ICMP_SLE:
6236 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6237 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006238 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006239 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006240 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241 break;
6242 case ICmpInst::ICMP_UGE:
6243 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6244 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006245 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006247 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 break;
6249 case ICmpInst::ICMP_ULE:
6250 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6251 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006252 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006254 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006255 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006256 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006257
6258 // Turn a signed comparison into an unsigned one if both operands
6259 // are known to have the same sign.
6260 if (I.isSignedPredicate() &&
6261 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6262 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006263 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006264 }
6265
6266 // Test if the ICmpInst instruction is used exclusively by a select as
6267 // part of a minimum or maximum operation. If so, refrain from doing
6268 // any other folding. This helps out other analyses which understand
6269 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6270 // and CodeGen. And in this case, at least one of the comparison
6271 // operands has at least one user besides the compare (the select),
6272 // which would often largely negate the benefit of folding anyway.
6273 if (I.hasOneUse())
6274 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6275 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6276 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6277 return 0;
6278
6279 // See if we are doing a comparison between a constant and an instruction that
6280 // can be folded into the comparison.
6281 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006282 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006283 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006284 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006285 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006286 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6287 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006288 }
6289
Chris Lattner01deb9d2007-04-03 17:43:25 +00006290 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006291 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6292 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6293 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006294 case Instruction::GetElementPtr:
6295 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006297 bool isAllZeros = true;
6298 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6299 if (!isa<Constant>(LHSI->getOperand(i)) ||
6300 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6301 isAllZeros = false;
6302 break;
6303 }
6304 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006305 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006306 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006307 }
6308 break;
6309
Chris Lattner6970b662005-04-23 15:31:55 +00006310 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006311 // Only fold icmp into the PHI if the phi and fcmp are in the same
6312 // block. If in the same block, we're encouraging jump threading. If
6313 // not, we are just pessimizing the code by making an i1 phi.
6314 if (LHSI->getParent() == I.getParent())
6315 if (Instruction *NV = FoldOpIntoPhi(I))
6316 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006317 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006318 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006319 // If either operand of the select is a constant, we can fold the
6320 // comparison into the select arms, which will cause one to be
6321 // constant folded and the select turned into a bitwise or.
6322 Value *Op1 = 0, *Op2 = 0;
6323 if (LHSI->hasOneUse()) {
6324 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6325 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006326 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006327 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006328 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006329 LHSI->getOperand(2), RHSC,
6330 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006331 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6332 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006333 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006334 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006335 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 LHSI->getOperand(1), RHSC,
6337 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006338 }
6339 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006340
Chris Lattner6970b662005-04-23 15:31:55 +00006341 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006342 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006343 break;
6344 }
Chris Lattner4802d902007-04-06 18:57:34 +00006345 case Instruction::Malloc:
6346 // If we have (malloc != null), and if the malloc has a single use, we
6347 // can assume it is successful and remove the malloc.
6348 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6349 AddToWorkList(LHSI);
Owen Andersoneed707b2009-07-24 23:12:02 +00006350 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006351 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006352 }
6353 break;
6354 }
Chris Lattner6970b662005-04-23 15:31:55 +00006355 }
6356
Reid Spencere4d87aa2006-12-23 06:05:41 +00006357 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006358 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006360 return NI;
6361 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006362 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6363 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006364 return NI;
6365
Reid Spencere4d87aa2006-12-23 06:05:41 +00006366 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006367 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6368 // now.
6369 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6370 if (isa<PointerType>(Op0->getType()) &&
6371 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006372 // We keep moving the cast from the left operand over to the right
6373 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006374 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006375
Chris Lattner57d86372007-01-06 01:45:59 +00006376 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6377 // so eliminate it as well.
6378 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6379 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006380
Chris Lattnerde90b762003-11-03 04:25:02 +00006381 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006382 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006383 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006384 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006385 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006386 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006387 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006388 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006389 }
Owen Anderson333c4002009-07-09 23:48:35 +00006390 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006391 }
Chris Lattner57d86372007-01-06 01:45:59 +00006392 }
6393
6394 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006395 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006396 // This comes up when you have code like
6397 // int X = A < B;
6398 // if (X) ...
6399 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006400 // with a constant or another cast from the same type.
6401 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006402 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006403 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006404 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006405
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006406 // See if it's the same type of instruction on the left and right.
6407 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6408 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006409 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006410 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006411 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006412 default: break;
6413 case Instruction::Add:
6414 case Instruction::Sub:
6415 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006416 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006417 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006418 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006419 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6421 if (CI->getValue().isSignBit()) {
6422 ICmpInst::Predicate Pred = I.isSignedPredicate()
6423 ? I.getUnsignedPredicate()
6424 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006425 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006426 Op1I->getOperand(0));
6427 }
6428
6429 if (CI->getValue().isMaxSignedValue()) {
6430 ICmpInst::Predicate Pred = I.isSignedPredicate()
6431 ? I.getUnsignedPredicate()
6432 : I.getSignedPredicate();
6433 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006434 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006435 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006436 }
6437 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006438 break;
6439 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006440 if (!I.isEquality())
6441 break;
6442
Nick Lewycky5d52c452008-08-21 05:56:10 +00006443 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6444 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6445 // Mask = -1 >> count-trailing-zeros(Cst).
6446 if (!CI->isZero() && !CI->isOne()) {
6447 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006448 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006449 APInt::getLowBitsSet(AP.getBitWidth(),
6450 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006451 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006452 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6453 Mask);
6454 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6455 Mask);
6456 InsertNewInstBefore(And1, I);
6457 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006458 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006459 }
6460 }
6461 break;
6462 }
6463 }
6464 }
6465 }
6466
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006467 // ~x < ~y --> y < x
6468 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006469 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6470 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006471 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006472 }
6473
Chris Lattner65b72ba2006-09-18 04:22:48 +00006474 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006475 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006476
6477 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006478 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6479 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006480 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006481
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006482 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006483 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6484 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006485 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006486 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006487 }
6488
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006489 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006490 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006491 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006492 if (match(B, m_ConstantInt(C1), *Context) &&
6493 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006494 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006495 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006496 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006497 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006498 InsertNewInstBefore(Xor, I));
6499 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006500
6501 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006502 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6503 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6504 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6505 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006506 }
6507 }
6508
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006509 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006510 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006511 // A == (A^B) -> B == 0
6512 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006513 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006514 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006515 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006516
6517 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006518 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006519 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006520 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006521
6522 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006523 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006524 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006525 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006526
Chris Lattner9c2328e2006-11-14 06:06:06 +00006527 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6528 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006529 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6530 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006531 Value *X = 0, *Y = 0, *Z = 0;
6532
6533 if (A == C) {
6534 X = B; Y = D; Z = A;
6535 } else if (A == D) {
6536 X = B; Y = C; Z = A;
6537 } else if (B == C) {
6538 X = A; Y = D; Z = B;
6539 } else if (B == D) {
6540 X = A; Y = C; Z = B;
6541 }
6542
6543 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006544 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6545 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006546 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006547 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006548 return &I;
6549 }
6550 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006551 }
Chris Lattner7e708292002-06-25 16:13:24 +00006552 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006553}
6554
Chris Lattner562ef782007-06-20 23:46:26 +00006555
6556/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6557/// and CmpRHS are both known to be integer constants.
6558Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6559 ConstantInt *DivRHS) {
6560 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6561 const APInt &CmpRHSV = CmpRHS->getValue();
6562
6563 // FIXME: If the operand types don't match the type of the divide
6564 // then don't attempt this transform. The code below doesn't have the
6565 // logic to deal with a signed divide and an unsigned compare (and
6566 // vice versa). This is because (x /s C1) <s C2 produces different
6567 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6568 // (x /u C1) <u C2. Simply casting the operands and result won't
6569 // work. :( The if statement below tests that condition and bails
6570 // if it finds it.
6571 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6572 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6573 return 0;
6574 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006576 if (DivIsSigned && DivRHS->isAllOnesValue())
6577 return 0; // The overflow computation also screws up here
6578 if (DivRHS->isOne())
6579 return 0; // Not worth bothering, and eliminates some funny cases
6580 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006581
6582 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6583 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6584 // C2 (CI). By solving for X we can turn this into a range check
6585 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006586 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006587
6588 // Determine if the product overflows by seeing if the product is
6589 // not equal to the divide. Make sure we do the same kind of divide
6590 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006591 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6592 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006593
6594 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006595 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006596
Chris Lattner1dbfd482007-06-21 18:11:19 +00006597 // Figure out the interval that is being checked. For example, a comparison
6598 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6599 // Compute this interval based on the constants involved and the signedness of
6600 // the compare/divide. This computes a half-open interval, keeping track of
6601 // whether either value in the interval overflows. After analysis each
6602 // overflow variable is set to 0 if it's corresponding bound variable is valid
6603 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6604 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006605 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006606
Chris Lattner562ef782007-06-20 23:46:26 +00006607 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006609 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006610 HiOverflow = LoOverflow = ProdOV;
6611 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006612 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006613 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006614 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006615 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006616 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6617 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006618 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006619 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006620 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6621 HiOverflow = LoOverflow = ProdOV;
6622 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006623 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006624 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006625 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006626 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006627 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6628 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006629 ConstantInt* DivNeg =
6630 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6631 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006632 true) ? -1 : 0;
6633 }
Chris Lattner562ef782007-06-20 23:46:26 +00006634 }
Dan Gohman76491272008-02-13 22:09:18 +00006635 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006636 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006637 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006638 LoBound = AddOne(DivRHS, Context);
6639 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6641 HiOverflow = 1; // [INTMIN+1, overflow)
6642 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6643 }
Dan Gohman76491272008-02-13 22:09:18 +00006644 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006645 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006646 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006647 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006648 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006649 LoOverflow = AddWithOverflow(LoBound, HiBound,
6650 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006651 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006652 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6653 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006654 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006655 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006656 }
6657
Chris Lattner1dbfd482007-06-21 18:11:19 +00006658 // Dividing by a negative swaps the condition. LT <-> GT
6659 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006660 }
6661
6662 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006663 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006664 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006665 case ICmpInst::ICMP_EQ:
6666 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006667 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006668 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006669 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006670 ICmpInst::ICMP_UGE, X, LoBound);
6671 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006672 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006673 ICmpInst::ICMP_ULT, X, HiBound);
6674 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006675 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006676 case ICmpInst::ICMP_NE:
6677 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006678 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006679 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006680 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006681 ICmpInst::ICMP_ULT, X, LoBound);
6682 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006683 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006684 ICmpInst::ICMP_UGE, X, HiBound);
6685 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006686 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006687 case ICmpInst::ICMP_ULT:
6688 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006689 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006690 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006691 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006692 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006693 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006694 case ICmpInst::ICMP_UGT:
6695 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006696 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006697 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006698 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006699 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006700 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006701 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006702 else
Owen Anderson333c4002009-07-09 23:48:35 +00006703 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006704 }
6705}
6706
6707
Chris Lattner01deb9d2007-04-03 17:43:25 +00006708/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6709///
6710Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6711 Instruction *LHSI,
6712 ConstantInt *RHS) {
6713 const APInt &RHSV = RHS->getValue();
6714
6715 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006716 case Instruction::Trunc:
6717 if (ICI.isEquality() && LHSI->hasOneUse()) {
6718 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6719 // of the high bits truncated out of x are known.
6720 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6721 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6722 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6723 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6724 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6725
6726 // If all the high bits are known, we can do this xform.
6727 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6728 // Pull in the high bits from known-ones set.
6729 APInt NewRHS(RHS->getValue());
6730 NewRHS.zext(SrcBits);
6731 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006732 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006733 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006734 }
6735 }
6736 break;
6737
Duncan Sands0091bf22007-04-04 06:42:45 +00006738 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006739 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6740 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6741 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006742 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6743 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006744 Value *CompareVal = LHSI->getOperand(0);
6745
6746 // If the sign bit of the XorCST is not set, there is no change to
6747 // the operation, just stop using the Xor.
6748 if (!XorCST->getValue().isNegative()) {
6749 ICI.setOperand(0, CompareVal);
6750 AddToWorkList(LHSI);
6751 return &ICI;
6752 }
6753
6754 // Was the old condition true if the operand is positive?
6755 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6756
6757 // If so, the new one isn't.
6758 isTrueIfPositive ^= true;
6759
6760 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006761 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006762 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006763 else
Owen Anderson333c4002009-07-09 23:48:35 +00006764 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006765 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006766 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006767
6768 if (LHSI->hasOneUse()) {
6769 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6770 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6771 const APInt &SignBit = XorCST->getValue();
6772 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6773 ? ICI.getUnsignedPredicate()
6774 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006775 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006776 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006777 }
6778
6779 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006780 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006781 const APInt &NotSignBit = XorCST->getValue();
6782 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6783 ? ICI.getUnsignedPredicate()
6784 : ICI.getSignedPredicate();
6785 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006786 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006787 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006788 }
6789 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006790 }
6791 break;
6792 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6793 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6794 LHSI->getOperand(0)->hasOneUse()) {
6795 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6796
6797 // If the LHS is an AND of a truncating cast, we can widen the
6798 // and/compare to be the input width without changing the value
6799 // produced, eliminating a cast.
6800 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6801 // We can do this transformation if either the AND constant does not
6802 // have its sign bit set or if it is an equality comparison.
6803 // Extending a relational comparison when we're checking the sign
6804 // bit would not work.
6805 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006806 (ICI.isEquality() ||
6807 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006808 uint32_t BitWidth =
6809 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6810 APInt NewCST = AndCST->getValue();
6811 NewCST.zext(BitWidth);
6812 APInt NewCI = RHSV;
6813 NewCI.zext(BitWidth);
6814 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006815 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006816 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006817 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006818 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006819 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006820 }
6821 }
6822
6823 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6824 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6825 // happens a LOT in code produced by the C front-end, for bitfield
6826 // access.
6827 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6828 if (Shift && !Shift->isShift())
6829 Shift = 0;
6830
6831 ConstantInt *ShAmt;
6832 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6833 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6834 const Type *AndTy = AndCST->getType(); // Type of the and.
6835
6836 // We can fold this as long as we can't shift unknown bits
6837 // into the mask. This can only happen with signed shift
6838 // rights, as they sign-extend.
6839 if (ShAmt) {
6840 bool CanFold = Shift->isLogicalShift();
6841 if (!CanFold) {
6842 // To test for the bad case of the signed shr, see if any
6843 // of the bits shifted in could be tested after the mask.
6844 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6845 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6846
6847 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6848 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6849 AndCST->getValue()) == 0)
6850 CanFold = true;
6851 }
6852
6853 if (CanFold) {
6854 Constant *NewCst;
6855 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006856 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006857 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006858 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006859
6860 // Check to see if we are shifting out any of the bits being
6861 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006862 if (Context->getConstantExpr(Shift->getOpcode(),
6863 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006864 // If we shifted bits out, the fold is not going to work out.
6865 // As a special case, check to see if this means that the
6866 // result is always true or false now.
6867 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006868 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006870 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006871 } else {
6872 ICI.setOperand(1, NewCst);
6873 Constant *NewAndCST;
6874 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006875 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006876 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006877 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006878 LHSI->setOperand(1, NewAndCST);
6879 LHSI->setOperand(0, Shift->getOperand(0));
6880 AddToWorkList(Shift); // Shift is dead.
6881 AddUsesToWorkList(ICI);
6882 return &ICI;
6883 }
6884 }
6885 }
6886
6887 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6888 // preferable because it allows the C<<Y expression to be hoisted out
6889 // of a loop if Y is invariant and X is not.
6890 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006891 ICI.isEquality() && !Shift->isArithmeticShift() &&
6892 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006893 // Compute C << Y.
6894 Value *NS;
6895 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006896 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006897 Shift->getOperand(1), "tmp");
6898 } else {
6899 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006900 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006901 Shift->getOperand(1), "tmp");
6902 }
6903 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6904
6905 // Compute X & (C << Y).
6906 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006907 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006908 InsertNewInstBefore(NewAnd, ICI);
6909
6910 ICI.setOperand(0, NewAnd);
6911 return &ICI;
6912 }
6913 }
6914 break;
6915
Chris Lattnera0141b92007-07-15 20:42:37 +00006916 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6917 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6918 if (!ShAmt) break;
6919
6920 uint32_t TypeBits = RHSV.getBitWidth();
6921
6922 // Check that the shift amount is in range. If not, don't perform
6923 // undefined shifts. When the shift is visited it will be
6924 // simplified.
6925 if (ShAmt->uge(TypeBits))
6926 break;
6927
6928 if (ICI.isEquality()) {
6929 // If we are comparing against bits always shifted out, the
6930 // comparison cannot succeed.
6931 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006932 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6933 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006934 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6935 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006936 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006937 return ReplaceInstUsesWith(ICI, Cst);
6938 }
6939
6940 if (LHSI->hasOneUse()) {
6941 // Otherwise strength reduce the shift into an and.
6942 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6943 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006944 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006945 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006946
Chris Lattnera0141b92007-07-15 20:42:37 +00006947 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006948 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006949 Mask, LHSI->getName()+".mask");
6950 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006951 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006952 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006953 }
6954 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006955
6956 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6957 bool TrueIfSigned = false;
6958 if (LHSI->hasOneUse() &&
6959 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6960 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006961 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 (TypeBits-ShAmt->getZExtValue()-1));
6963 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006964 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006965 Mask, LHSI->getName()+".mask");
6966 Value *And = InsertNewInstBefore(AndI, ICI);
6967
Owen Anderson333c4002009-07-09 23:48:35 +00006968 return new ICmpInst(*Context,
6969 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006970 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006971 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006972 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006973 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006974
6975 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006976 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006978 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006979 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006980
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006981 // Check that the shift amount is in range. If not, don't perform
6982 // undefined shifts. When the shift is visited it will be
6983 // simplified.
6984 uint32_t TypeBits = RHSV.getBitWidth();
6985 if (ShAmt->uge(TypeBits))
6986 break;
6987
6988 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006989
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006990 // If we are comparing against bits always shifted out, the
6991 // comparison cannot succeed.
6992 APInt Comp = RHSV << ShAmtVal;
6993 if (LHSI->getOpcode() == Instruction::LShr)
6994 Comp = Comp.lshr(ShAmtVal);
6995 else
6996 Comp = Comp.ashr(ShAmtVal);
6997
6998 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6999 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00007000 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007001 return ReplaceInstUsesWith(ICI, Cst);
7002 }
7003
7004 // Otherwise, check to see if the bits shifted out are known to be zero.
7005 // If so, we can compare against the unshifted value:
7006 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007007 if (LHSI->hasOneUse() &&
7008 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007010 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007011 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007012 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007013
Evan Chengf30752c2008-04-23 00:38:06 +00007014 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007015 // Otherwise strength reduce the shift into an and.
7016 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007017 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007018
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007019 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007020 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007021 Mask, LHSI->getName()+".mask");
7022 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007023 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007024 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025 }
7026 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007027 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007028
7029 case Instruction::SDiv:
7030 case Instruction::UDiv:
7031 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7032 // Fold this div into the comparison, producing a range check.
7033 // Determine, based on the divide type, what the range is being
7034 // checked. If there is an overflow on the low or high side, remember
7035 // it, otherwise compute the range [low, hi) bounding the new value.
7036 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007037 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7038 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7039 DivRHS))
7040 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007041 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007042
7043 case Instruction::Add:
7044 // Fold: icmp pred (add, X, C1), C2
7045
7046 if (!ICI.isEquality()) {
7047 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7048 if (!LHSC) break;
7049 const APInt &LHSV = LHSC->getValue();
7050
7051 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7052 .subtract(LHSV);
7053
7054 if (ICI.isSignedPredicate()) {
7055 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007056 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007057 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007058 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007059 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007060 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007061 }
7062 } else {
7063 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007064 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007065 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007066 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007067 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007068 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007069 }
7070 }
7071 }
7072 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007073 }
7074
7075 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7076 if (ICI.isEquality()) {
7077 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7078
7079 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7080 // the second operand is a constant, simplify a bit.
7081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7082 switch (BO->getOpcode()) {
7083 case Instruction::SRem:
7084 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7085 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7086 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7087 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7088 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007089 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090 BO->getName());
7091 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007092 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007093 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007094 }
7095 }
7096 break;
7097 case Instruction::Add:
7098 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7099 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7100 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007101 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007102 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103 } else if (RHSV == 0) {
7104 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7105 // efficiently invertible, or if the add has just this one use.
7106 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7107
Owen Andersond672ecb2009-07-03 00:17:18 +00007108 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007109 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007110 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007111 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007112 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007113 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007114 InsertNewInstBefore(Neg, ICI);
7115 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007116 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007117 }
7118 }
7119 break;
7120 case Instruction::Xor:
7121 // For the xor case, we can xor two constants together, eliminating
7122 // the explicit xor.
7123 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007124 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007125 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126
7127 // FALLTHROUGH
7128 case Instruction::Sub:
7129 // Replace (([sub|xor] A, B) != 0) with (A != B)
7130 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007131 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007132 BO->getOperand(1));
7133 break;
7134
7135 case Instruction::Or:
7136 // If bits are being or'd in that are not present in the constant we
7137 // are comparing against, then the comparison could never succeed!
7138 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007139 Constant *NotCI = Context->getConstantExprNot(RHS);
7140 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7141 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007142 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007143 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007144 }
7145 break;
7146
7147 case Instruction::And:
7148 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7149 // If bits are being compared against that are and'd out, then the
7150 // comparison can never succeed!
7151 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007152 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007153 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007154 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155
7156 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7157 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007158 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007159 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007160 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161
7162 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007163 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007164 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007165 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166 ICmpInst::Predicate pred = isICMP_NE ?
7167 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007168 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 }
7170
7171 // ((X & ~7) == 0) --> X < 8
7172 if (RHSV == 0 && isHighOnes(BOC)) {
7173 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007174 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007175 ICmpInst::Predicate pred = isICMP_NE ?
7176 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007177 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007178 }
7179 }
7180 default: break;
7181 }
7182 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7183 // Handle icmp {eq|ne} <intrinsic>, intcst.
7184 if (II->getIntrinsicID() == Intrinsic::bswap) {
7185 AddToWorkList(II);
7186 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007187 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007188 return &ICI;
7189 }
7190 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007191 }
7192 return 0;
7193}
7194
7195/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7196/// We only handle extending casts so far.
7197///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007198Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7199 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007200 Value *LHSCIOp = LHSCI->getOperand(0);
7201 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007202 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007203 Value *RHSCIOp;
7204
Chris Lattner8c756c12007-05-05 22:41:33 +00007205 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7206 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007207 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7208 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007209 cast<IntegerType>(DestTy)->getBitWidth()) {
7210 Value *RHSOp = 0;
7211 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007212 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007213 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7214 RHSOp = RHSC->getOperand(0);
7215 // If the pointer types don't match, insert a bitcast.
7216 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007217 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007218 }
7219
7220 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007221 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007222 }
7223
7224 // The code below only handles extension cast instructions, so far.
7225 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007226 if (LHSCI->getOpcode() != Instruction::ZExt &&
7227 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007228 return 0;
7229
Reid Spencere4d87aa2006-12-23 06:05:41 +00007230 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7231 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007232
Reid Spencere4d87aa2006-12-23 06:05:41 +00007233 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007234 // Not an extension from the same type?
7235 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007236 if (RHSCIOp->getType() != LHSCIOp->getType())
7237 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007238
Nick Lewycky4189a532008-01-28 03:48:02 +00007239 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007240 // and the other is a zext), then we can't handle this.
7241 if (CI->getOpcode() != LHSCI->getOpcode())
7242 return 0;
7243
Nick Lewycky4189a532008-01-28 03:48:02 +00007244 // Deal with equality cases early.
7245 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007246 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007247
7248 // A signed comparison of sign extended values simplifies into a
7249 // signed comparison.
7250 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007251 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007252
7253 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007254 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007255 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007256
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 // If we aren't dealing with a constant on the RHS, exit early
7258 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7259 if (!CI)
7260 return 0;
7261
7262 // Compute the constant that would happen if we truncated to SrcTy then
7263 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007264 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7265 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7266 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267
7268 // If the re-extended constant didn't change...
7269 if (Res2 == CI) {
7270 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7271 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007272 // %A = sext i16 %X to i32
7273 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007274 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007275 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007276 // because %A may have negative value.
7277 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007278 // However, we allow this when the compare is EQ/NE, because they are
7279 // signless.
7280 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007281 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007282 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007283 }
7284
7285 // The re-extended constant changed so the constant cannot be represented
7286 // in the shorter type. Consequently, we cannot emit a simple comparison.
7287
7288 // First, handle some easy cases. We know the result cannot be equal at this
7289 // point so handle the ICI.isEquality() cases
7290 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007291 return ReplaceInstUsesWith(ICI, Context->getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007292 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007293 return ReplaceInstUsesWith(ICI, Context->getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007294
7295 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7296 // should have been folded away previously and not enter in here.
7297 Value *Result;
7298 if (isSignedCmp) {
7299 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007300 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00007301 Result = Context->getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007302 else
Owen Andersonb3056fa2009-07-21 18:03:38 +00007303 Result = Context->getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007304 } else {
7305 // We're performing an unsigned comparison.
7306 if (isSignedExt) {
7307 // We're performing an unsigned comp with a sign extended value.
7308 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007309 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007310 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7311 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 } else {
7313 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb3056fa2009-07-21 18:03:38 +00007314 Result = Context->getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007315 }
7316 }
7317
7318 // Finally, return the value computed.
7319 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007320 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007321 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007322
7323 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7324 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7325 "ICmp should be folded!");
7326 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007327 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007328 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007329}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007330
Reid Spencer832254e2007-02-02 02:16:23 +00007331Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7332 return commonShiftTransforms(I);
7333}
7334
7335Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7336 return commonShiftTransforms(I);
7337}
7338
7339Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007340 if (Instruction *R = commonShiftTransforms(I))
7341 return R;
7342
7343 Value *Op0 = I.getOperand(0);
7344
7345 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7346 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7347 if (CSI->isAllOnesValue())
7348 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007349
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007350 // See if we can turn a signed shr into an unsigned shr.
7351 if (MaskedValueIsZero(Op0,
7352 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7353 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7354
7355 // Arithmetic shifting an all-sign-bit value is a no-op.
7356 unsigned NumSignBits = ComputeNumSignBits(Op0);
7357 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7358 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007359
Chris Lattner348f6652007-12-06 01:59:46 +00007360 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007361}
7362
7363Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7364 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007365 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007366
7367 // shl X, 0 == X and shr X, 0 == X
7368 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007369 if (Op1 == Context->getNullValue(Op1->getType()) ||
7370 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007371 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007372
Reid Spencere4d87aa2006-12-23 06:05:41 +00007373 if (isa<UndefValue>(Op0)) {
7374 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007375 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007376 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007377 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007378 }
7379 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007380 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7381 return ReplaceInstUsesWith(I, Op0);
7382 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007383 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007384 }
7385
Dan Gohman9004c8a2009-05-21 02:28:33 +00007386 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007387 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007388 return &I;
7389
Chris Lattner2eefe512004-04-09 19:05:30 +00007390 // Try to fold constant and into select arguments.
7391 if (isa<Constant>(Op0))
7392 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007394 return R;
7395
Reid Spencerb83eb642006-10-20 07:07:24 +00007396 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007397 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7398 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007399 return 0;
7400}
7401
Reid Spencerb83eb642006-10-20 07:07:24 +00007402Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007403 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007404 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007405
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007406 // See if we can simplify any instructions used by the instruction whose sole
7407 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007408 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007409
Dan Gohmana119de82009-06-14 23:30:43 +00007410 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7411 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007413 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007414 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007415 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007416 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007417 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007418 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007419 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007420 }
7421
7422 // ((X*C1) << C2) == (X * (C1 << C2))
7423 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7424 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7425 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007426 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007427 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007428
7429 // Try to fold constant and into select arguments.
7430 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7432 return R;
7433 if (isa<PHINode>(Op0))
7434 if (Instruction *NV = FoldOpIntoPhi(I))
7435 return NV;
7436
Chris Lattner8999dd32007-12-22 09:07:47 +00007437 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7438 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7439 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7440 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7441 // place. Don't try to do this transformation in this case. Also, we
7442 // require that the input operand is a shift-by-constant so that we have
7443 // confidence that the shifts will get folded together. We could do this
7444 // xform in more cases, but it is unlikely to be profitable.
7445 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7446 isa<ConstantInt>(TrOp->getOperand(1))) {
7447 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007448 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007449 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007450 I.getName());
7451 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7452
7453 // For logical shifts, the truncation has the effect of making the high
7454 // part of the register be zeros. Emulate this by inserting an AND to
7455 // clear the top bits as needed. This 'and' will usually be zapped by
7456 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007457 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7458 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007459 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7460
7461 // The mask we constructed says what the trunc would do if occurring
7462 // between the shifts. We want to know the effect *after* the second
7463 // shift. We know that it is a logical shift by a constant, so adjust the
7464 // mask as appropriate.
7465 if (I.getOpcode() == Instruction::Shl)
7466 MaskV <<= Op1->getZExtValue();
7467 else {
7468 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7469 MaskV = MaskV.lshr(Op1->getZExtValue());
7470 }
7471
Owen Andersond672ecb2009-07-03 00:17:18 +00007472 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007473 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007474 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007475 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7476
7477 // Return the value truncated to the interesting size.
7478 return new TruncInst(And, I.getType());
7479 }
7480 }
7481
Chris Lattner4d5542c2006-01-06 07:12:35 +00007482 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007483 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7484 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7485 Value *V1, *V2;
7486 ConstantInt *CC;
7487 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007488 default: break;
7489 case Instruction::Add:
7490 case Instruction::And:
7491 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007492 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007493 // These operators commute.
7494 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007495 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007496 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7497 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007498 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007499 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 Op0BO->getName());
7501 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007502 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007503 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007504 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007506 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007507 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007508 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007509 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007510
Chris Lattner150f12a2005-09-18 06:30:59 +00007511 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007512 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007513 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007514 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007515 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007516 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007517 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007518 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007519 Op0BO->getOperand(0), Op1,
7520 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007521 InsertNewInstBefore(YS, I); // (Y << C)
7522 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007523 BinaryOperator::CreateAnd(V1,
7524 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007525 V1->getName()+".mask");
7526 InsertNewInstBefore(XM, I); // X & (CC << C)
7527
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007528 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007530 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007531
Reid Spencera07cb7d2007-02-02 14:41:37 +00007532 // FALL THROUGH.
7533 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007534 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007536 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7537 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007538 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007539 Op0BO->getOperand(1), Op1,
7540 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007541 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007542 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007544 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007545 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007546 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007547 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007548 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007549 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007550
Chris Lattner13d4ab42006-05-31 21:14:00 +00007551 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007552 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7553 match(Op0BO->getOperand(0),
7554 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007555 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007556 cast<BinaryOperator>(Op0BO->getOperand(0))
7557 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007558 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007559 Op0BO->getOperand(1), Op1,
7560 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007561 InsertNewInstBefore(YS, I); // (Y << C)
7562 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007563 BinaryOperator::CreateAnd(V1,
7564 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007565 V1->getName()+".mask");
7566 InsertNewInstBefore(XM, I); // X & (CC << C)
7567
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007568 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007569 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570
Chris Lattner11021cb2005-09-18 05:12:10 +00007571 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007572 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007573 }
7574
7575
7576 // If the operand is an bitwise operator with a constant RHS, and the
7577 // shift is the only use, we can pull it out of the shift.
7578 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7579 bool isValid = true; // Valid only for And, Or, Xor
7580 bool highBitSet = false; // Transform if high bit of constant set?
7581
7582 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007583 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007584 case Instruction::Add:
7585 isValid = isLeftShift;
7586 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007587 case Instruction::Or:
7588 case Instruction::Xor:
7589 highBitSet = false;
7590 break;
7591 case Instruction::And:
7592 highBitSet = true;
7593 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007594 }
7595
7596 // If this is a signed shift right, and the high bit is modified
7597 // by the logical operation, do not perform the transformation.
7598 // The highBitSet boolean indicates the value of the high bit of
7599 // the constant which would cause it to be modified for this
7600 // operation.
7601 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007602 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007603 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007604
7605 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007606 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007607
7608 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007609 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007610 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007611 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007612
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007613 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007614 NewRHS);
7615 }
7616 }
7617 }
7618 }
7619
Chris Lattnerad0124c2006-01-06 07:52:12 +00007620 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007621 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7622 if (ShiftOp && !ShiftOp->isShift())
7623 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007624
Reid Spencerb83eb642006-10-20 07:07:24 +00007625 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007626 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007627 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7628 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007629 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7630 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7631 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007632
Zhou Sheng4351c642007-04-02 08:20:41 +00007633 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634
7635 const IntegerType *Ty = cast<IntegerType>(I.getType());
7636
7637 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007638 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007639 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7640 // saturates.
7641 if (AmtSum >= TypeBits) {
7642 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007643 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007644 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7645 }
7646
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007647 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007648 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007649 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7650 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007651 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007652 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007653
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007655 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007656 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7657 I.getOpcode() == Instruction::LShr) {
7658 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007659 if (AmtSum >= TypeBits)
7660 AmtSum = TypeBits-1;
7661
Chris Lattnerb87056f2007-02-05 00:57:54 +00007662 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007663 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664 InsertNewInstBefore(Shift, I);
7665
Zhou Shenge9e03f62007-03-28 15:02:20 +00007666 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007667 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007668 }
7669
Chris Lattnerb87056f2007-02-05 00:57:54 +00007670 // Okay, if we get here, one shift must be left, and the other shift must be
7671 // right. See if the amounts are equal.
7672 if (ShiftAmt1 == ShiftAmt2) {
7673 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7674 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007675 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007676 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007677 }
7678 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7679 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007680 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007681 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007682 }
7683 // We can simplify ((X << C) >>s C) into a trunc + sext.
7684 // NOTE: we could do this for any C, but that would make 'unusual' integer
7685 // types. For now, just stick to ones well-supported by the code
7686 // generators.
7687 const Type *SExtType = 0;
7688 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007689 case 1 :
7690 case 8 :
7691 case 16 :
7692 case 32 :
7693 case 64 :
7694 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007695 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007696 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007697 default: break;
7698 }
7699 if (SExtType) {
7700 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7701 InsertNewInstBefore(NewTrunc, I);
7702 return new SExtInst(NewTrunc, Ty);
7703 }
7704 // Otherwise, we can't handle it yet.
7705 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007706 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007707
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007708 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007709 if (I.getOpcode() == Instruction::Shl) {
7710 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7711 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007712 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007713 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007714 InsertNewInstBefore(Shift, I);
7715
Reid Spencer55702aa2007-03-25 21:11:44 +00007716 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007717 return BinaryOperator::CreateAnd(Shift,
7718 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007719 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007721 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722 if (I.getOpcode() == Instruction::LShr) {
7723 assert(ShiftOp->getOpcode() == Instruction::Shl);
7724 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007725 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007726 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007727
Reid Spencerd5e30f02007-03-26 17:18:58 +00007728 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007729 return BinaryOperator::CreateAnd(Shift,
7730 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007731 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007732
7733 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7734 } else {
7735 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007736 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007737
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007738 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007739 if (I.getOpcode() == Instruction::Shl) {
7740 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7741 ShiftOp->getOpcode() == Instruction::AShr);
7742 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007743 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007744 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007745 InsertNewInstBefore(Shift, I);
7746
Reid Spencer55702aa2007-03-25 21:11:44 +00007747 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007748 return BinaryOperator::CreateAnd(Shift,
7749 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007750 }
7751
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007752 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007753 if (I.getOpcode() == Instruction::LShr) {
7754 assert(ShiftOp->getOpcode() == Instruction::Shl);
7755 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007756 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007757 InsertNewInstBefore(Shift, I);
7758
Reid Spencer68d27cf2007-03-26 23:45:51 +00007759 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007760 return BinaryOperator::CreateAnd(Shift,
7761 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007762 }
7763
7764 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007765 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007766 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007767 return 0;
7768}
7769
Chris Lattnera1be5662002-05-02 17:06:02 +00007770
Chris Lattnercfd65102005-10-29 04:36:15 +00007771/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7772/// expression. If so, decompose it, returning some value X, such that Val is
7773/// X*Scale+Offset.
7774///
7775static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007776 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007777 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007778 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007779 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007780 Scale = 0;
Owen Andersoneed707b2009-07-24 23:12:02 +00007781 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007782 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7783 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7784 if (I->getOpcode() == Instruction::Shl) {
7785 // This is a value scaled by '1 << the shift amt'.
7786 Scale = 1U << RHS->getZExtValue();
7787 Offset = 0;
7788 return I->getOperand(0);
7789 } else if (I->getOpcode() == Instruction::Mul) {
7790 // This value is scaled by 'RHS'.
7791 Scale = RHS->getZExtValue();
7792 Offset = 0;
7793 return I->getOperand(0);
7794 } else if (I->getOpcode() == Instruction::Add) {
7795 // We have X+C. Check to see if we really have (X*C2)+C1,
7796 // where C1 is divisible by C2.
7797 unsigned SubScale;
7798 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007799 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7800 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007801 Offset += RHS->getZExtValue();
7802 Scale = SubScale;
7803 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007804 }
7805 }
7806 }
7807
7808 // Otherwise, we can't look past this.
7809 Scale = 1;
7810 Offset = 0;
7811 return Val;
7812}
7813
7814
Chris Lattnerb3f83972005-10-24 06:03:58 +00007815/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7816/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007817Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007818 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007819 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007820
Chris Lattnerb53c2382005-10-24 06:22:12 +00007821 // Remove any uses of AI that are dead.
7822 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007823
Chris Lattnerb53c2382005-10-24 06:22:12 +00007824 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7825 Instruction *User = cast<Instruction>(*UI++);
7826 if (isInstructionTriviallyDead(User)) {
7827 while (UI != E && *UI == User)
7828 ++UI; // If this instruction uses AI more than once, don't break UI.
7829
Chris Lattnerb53c2382005-10-24 06:22:12 +00007830 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007831 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007832 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007833 }
7834 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007835
7836 // This requires TargetData to get the alloca alignment and size information.
7837 if (!TD) return 0;
7838
Chris Lattnerb3f83972005-10-24 06:03:58 +00007839 // Get the type really allocated and the type casted to.
7840 const Type *AllocElTy = AI.getAllocatedType();
7841 const Type *CastElTy = PTy->getElementType();
7842 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007843
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007844 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7845 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007846 if (CastElTyAlign < AllocElTyAlign) return 0;
7847
Chris Lattner39387a52005-10-24 06:35:18 +00007848 // If the allocation has multiple uses, only promote it if we are strictly
7849 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007850 // same, we open the door to infinite loops of various kinds. (A reference
7851 // from a dbg.declare doesn't count as a use for this purpose.)
7852 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7853 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007854
Duncan Sands777d2302009-05-09 07:06:46 +00007855 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7856 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007857 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007858
Chris Lattner455fcc82005-10-29 03:19:53 +00007859 // See if we can satisfy the modulus by pulling a scale out of the array
7860 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007861 unsigned ArraySizeScale;
7862 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007863 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007864 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7865 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007866
Chris Lattner455fcc82005-10-29 03:19:53 +00007867 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7868 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007869 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7870 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007871
Chris Lattner455fcc82005-10-29 03:19:53 +00007872 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7873 Value *Amt = 0;
7874 if (Scale == 1) {
7875 Amt = NumElements;
7876 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007877 // If the allocation size is constant, form a constant mul expression
Owen Andersoneed707b2009-07-24 23:12:02 +00007878 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007879 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007880 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007881 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007882 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007883 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007884 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007885 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007886 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007887 }
7888
Jeff Cohen86796be2007-04-04 16:58:57 +00007889 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007890 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007891 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007892 Amt = InsertNewInstBefore(Tmp, AI);
7893 }
7894
Chris Lattnerb3f83972005-10-24 06:03:58 +00007895 AllocationInst *New;
7896 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007897 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007898 else
Owen Anderson50dead02009-07-15 23:53:25 +00007899 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007900 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007901 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007902
Dale Johannesena0a66372009-03-05 00:39:02 +00007903 // If the allocation has one real use plus a dbg.declare, just remove the
7904 // declare.
7905 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7906 EraseInstFromFunction(*DI);
7907 }
7908 // If the allocation has multiple real uses, insert a cast and change all
7909 // things that used it to use the new cast. This will also hack on CI, but it
7910 // will die soon.
7911 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007912 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 // New is the allocation instruction, pointer typed. AI is the original
7914 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7915 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007916 InsertNewInstBefore(NewCast, AI);
7917 AI.replaceAllUsesWith(NewCast);
7918 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007919 return ReplaceInstUsesWith(CI, New);
7920}
7921
Chris Lattner70074e02006-05-13 02:06:03 +00007922/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007923/// and return it as type Ty without inserting any new casts and without
7924/// changing the computed value. This is used by code that tries to decide
7925/// whether promoting or shrinking integer operations to wider or smaller types
7926/// will allow us to eliminate a truncate or extend.
7927///
7928/// This is a truncation operation if Ty is smaller than V->getType(), or an
7929/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007930///
7931/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7932/// should return true if trunc(V) can be computed by computing V in the smaller
7933/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7934/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7935/// efficiently truncated.
7936///
7937/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7938/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7939/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007940bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007941 unsigned CastOpc,
7942 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007943 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007944 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007945 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007946
7947 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007948 if (!I) return false;
7949
Dan Gohman6de29f82009-06-15 22:12:54 +00007950 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007951
Chris Lattner951626b2007-08-02 06:11:14 +00007952 // If this is an extension or truncate, we can often eliminate it.
7953 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7954 // If this is a cast from the destination type, we can trivially eliminate
7955 // it, and this will remove a cast overall.
7956 if (I->getOperand(0)->getType() == Ty) {
7957 // If the first operand is itself a cast, and is eliminable, do not count
7958 // this as an eliminable cast. We would prefer to eliminate those two
7959 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007960 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007961 ++NumCastsRemoved;
7962 return true;
7963 }
7964 }
7965
7966 // We can't extend or shrink something that has multiple uses: doing so would
7967 // require duplicating the instruction in general, which isn't profitable.
7968 if (!I->hasOneUse()) return false;
7969
Evan Chengf35fd542009-01-15 17:01:23 +00007970 unsigned Opc = I->getOpcode();
7971 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007972 case Instruction::Add:
7973 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007974 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007975 case Instruction::And:
7976 case Instruction::Or:
7977 case Instruction::Xor:
7978 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007979 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007980 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007981 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007982 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007983
Eli Friedman070a9812009-07-13 22:46:01 +00007984 case Instruction::UDiv:
7985 case Instruction::URem: {
7986 // UDiv and URem can be truncated if all the truncated bits are zero.
7987 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7988 uint32_t BitWidth = Ty->getScalarSizeInBits();
7989 if (BitWidth < OrigBitWidth) {
7990 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7991 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7992 MaskedValueIsZero(I->getOperand(1), Mask)) {
7993 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7994 NumCastsRemoved) &&
7995 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7996 NumCastsRemoved);
7997 }
7998 }
7999 break;
8000 }
Chris Lattner46b96052006-11-29 07:18:39 +00008001 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008002 // If we are truncating the result of this SHL, and if it's a shift of a
8003 // constant amount, we can always perform a SHL in a smaller type.
8004 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008005 uint32_t BitWidth = Ty->getScalarSizeInBits();
8006 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008007 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008008 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008009 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008010 }
8011 break;
8012 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008013 // If this is a truncate of a logical shr, we can truncate it to a smaller
8014 // lshr iff we know that the bits we would otherwise be shifting in are
8015 // already zeros.
8016 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008017 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8018 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008019 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008020 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008021 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8022 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008023 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008024 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008025 }
8026 }
Chris Lattner46b96052006-11-29 07:18:39 +00008027 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008028 case Instruction::ZExt:
8029 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008030 case Instruction::Trunc:
8031 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008032 // can safely replace it. Note that replacing it does not reduce the number
8033 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008034 if (Opc == CastOpc)
8035 return true;
8036
8037 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008038 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008039 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008040 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008041 case Instruction::Select: {
8042 SelectInst *SI = cast<SelectInst>(I);
8043 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008044 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008045 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008046 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008047 }
Chris Lattner8114b712008-06-18 04:00:49 +00008048 case Instruction::PHI: {
8049 // We can change a phi if we can change all operands.
8050 PHINode *PN = cast<PHINode>(I);
8051 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8052 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008053 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008054 return false;
8055 return true;
8056 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008058 // TODO: Can handle more cases here.
8059 break;
8060 }
8061
8062 return false;
8063}
8064
8065/// EvaluateInDifferentType - Given an expression that
8066/// CanEvaluateInDifferentType returns true for, actually insert the code to
8067/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008068Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008069 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008070 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008071 return Context->getConstantExprIntegerCast(C, Ty,
8072 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008073
8074 // Otherwise, it must be an instruction.
8075 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008076 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008077 unsigned Opc = I->getOpcode();
8078 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008079 case Instruction::Add:
8080 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008081 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008082 case Instruction::And:
8083 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008084 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008085 case Instruction::AShr:
8086 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008087 case Instruction::Shl:
8088 case Instruction::UDiv:
8089 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008090 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008091 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008092 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008093 break;
8094 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 case Instruction::Trunc:
8096 case Instruction::ZExt:
8097 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008098 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008099 // just return the source. There's no need to insert it because it is not
8100 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008101 if (I->getOperand(0)->getType() == Ty)
8102 return I->getOperand(0);
8103
Chris Lattner8114b712008-06-18 04:00:49 +00008104 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008105 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008106 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008107 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008108 case Instruction::Select: {
8109 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8110 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8111 Res = SelectInst::Create(I->getOperand(0), True, False);
8112 break;
8113 }
Chris Lattner8114b712008-06-18 04:00:49 +00008114 case Instruction::PHI: {
8115 PHINode *OPN = cast<PHINode>(I);
8116 PHINode *NPN = PHINode::Create(Ty);
8117 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8118 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8119 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8120 }
8121 Res = NPN;
8122 break;
8123 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008124 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008125 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008126 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008127 break;
8128 }
8129
Chris Lattner8114b712008-06-18 04:00:49 +00008130 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008131 return InsertNewInstBefore(Res, *I);
8132}
8133
Reid Spencer3da59db2006-11-27 01:05:10 +00008134/// @brief Implement the transforms common to all CastInst visitors.
8135Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008136 Value *Src = CI.getOperand(0);
8137
Dan Gohman23d9d272007-05-11 21:10:54 +00008138 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008139 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008140 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008141 if (Instruction::CastOps opc =
8142 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8143 // The first cast (CSrc) is eliminable so we need to fix up or replace
8144 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008145 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008146 }
8147 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008148
Reid Spencer3da59db2006-11-27 01:05:10 +00008149 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008150 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8151 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8152 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008153
8154 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008155 if (isa<PHINode>(Src))
8156 if (Instruction *NV = FoldOpIntoPhi(CI))
8157 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008158
Reid Spencer3da59db2006-11-27 01:05:10 +00008159 return 0;
8160}
8161
Chris Lattner46cd5a12009-01-09 05:44:56 +00008162/// FindElementAtOffset - Given a type and a constant offset, determine whether
8163/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008164/// the specified offset. If so, fill them into NewIndices and return the
8165/// resultant element type, otherwise return null.
8166static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8167 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008168 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008169 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008170 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008171 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172
8173 // Start with the index over the outer type. Note that the type size
8174 // might be zero (even if the offset isn't zero) if the indexed type
8175 // is something like [0 x {int, int}]
8176 const Type *IntPtrTy = TD->getIntPtrType();
8177 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008178 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008179 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008180 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008181
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008182 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008183 if (Offset < 0) {
8184 --FirstIdx;
8185 Offset += TySize;
8186 assert(Offset >= 0);
8187 }
8188 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8189 }
8190
Owen Andersoneed707b2009-07-24 23:12:02 +00008191 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008192
8193 // Index into the types. If we fail, set OrigBase to null.
8194 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008195 // Indexing into tail padding between struct/array elements.
8196 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008197 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008198
Chris Lattner46cd5a12009-01-09 05:44:56 +00008199 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8200 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008201 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8202 "Offset must stay within the indexed type");
8203
Chris Lattner46cd5a12009-01-09 05:44:56 +00008204 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneed707b2009-07-24 23:12:02 +00008205 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008206
8207 Offset -= SL->getElementOffset(Elt);
8208 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008209 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008210 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008211 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008212 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008213 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008214 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008215 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008216 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008217 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008218 }
8219 }
8220
Chris Lattner3914f722009-01-24 01:00:13 +00008221 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222}
8223
Chris Lattnerd3e28342007-04-27 17:44:50 +00008224/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8225Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8226 Value *Src = CI.getOperand(0);
8227
Chris Lattnerd3e28342007-04-27 17:44:50 +00008228 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008229 // If casting the result of a getelementptr instruction with no offset, turn
8230 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008231 if (GEP->hasAllZeroIndices()) {
8232 // Changing the cast operand is usually not a good idea but it is safe
8233 // here because the pointer operand is being replaced with another
8234 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008235 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008236 CI.setOperand(0, GEP->getOperand(0));
8237 return &CI;
8238 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008239
8240 // If the GEP has a single use, and the base pointer is a bitcast, and the
8241 // GEP computes a constant offset, see if we can convert these three
8242 // instructions into fewer. This typically happens with unions and other
8243 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008244 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008245 if (GEP->hasAllConstantIndices()) {
8246 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008247 ConstantInt *OffsetV =
8248 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008249 int64_t Offset = OffsetV->getSExtValue();
8250
8251 // Get the base pointer input of the bitcast, and the type it points to.
8252 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8253 const Type *GEPIdxTy =
8254 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008255 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008256 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008257 // If we were able to index down into an element, create the GEP
8258 // and bitcast the result. This eliminates one bitcast, potentially
8259 // two.
8260 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8261 NewIndices.begin(),
8262 NewIndices.end(), "");
8263 InsertNewInstBefore(NGEP, CI);
8264 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008265
Chris Lattner46cd5a12009-01-09 05:44:56 +00008266 if (isa<BitCastInst>(CI))
8267 return new BitCastInst(NGEP, CI.getType());
8268 assert(isa<PtrToIntInst>(CI));
8269 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008270 }
8271 }
8272 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008273 }
8274
8275 return commonCastTransforms(CI);
8276}
8277
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008278/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8279/// type like i42. We don't want to introduce operations on random non-legal
8280/// integer types where they don't already exist in the code. In the future,
8281/// we should consider making this based off target-data, so that 32-bit targets
8282/// won't get i64 operations etc.
8283static bool isSafeIntegerType(const Type *Ty) {
8284 switch (Ty->getPrimitiveSizeInBits()) {
8285 case 8:
8286 case 16:
8287 case 32:
8288 case 64:
8289 return true;
8290 default:
8291 return false;
8292 }
8293}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008294
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008295/// commonIntCastTransforms - This function implements the common transforms
8296/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008297Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8298 if (Instruction *Result = commonCastTransforms(CI))
8299 return Result;
8300
8301 Value *Src = CI.getOperand(0);
8302 const Type *SrcTy = Src->getType();
8303 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008304 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8305 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008306
Reid Spencer3da59db2006-11-27 01:05:10 +00008307 // See if we can simplify any instructions used by the LHS whose sole
8308 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008309 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008310 return &CI;
8311
8312 // If the source isn't an instruction or has more than one use then we
8313 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008314 Instruction *SrcI = dyn_cast<Instruction>(Src);
8315 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008316 return 0;
8317
Chris Lattnerc739cd62007-03-03 05:27:34 +00008318 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008319 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008320 // Only do this if the dest type is a simple type, don't convert the
8321 // expression tree to something weird like i93 unless the source is also
8322 // strange.
8323 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008324 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8325 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008326 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008327 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008328 // eliminates the cast, so it is always a win. If this is a zero-extension,
8329 // we need to do an AND to maintain the clear top-part of the computation,
8330 // so we require that the input have eliminated at least one cast. If this
8331 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008332 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008333 bool DoXForm = false;
8334 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008335 switch (CI.getOpcode()) {
8336 default:
8337 // All the others use floating point so we shouldn't actually
8338 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008339 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008340 case Instruction::Trunc:
8341 DoXForm = true;
8342 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008343 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008344 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008345 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008346 // If it's unnecessary to issue an AND to clear the high bits, it's
8347 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008348 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008349 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8350 if (MaskedValueIsZero(TryRes, Mask))
8351 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008352
8353 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008354 if (TryI->use_empty())
8355 EraseInstFromFunction(*TryI);
8356 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008357 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008358 }
Evan Chengf35fd542009-01-15 17:01:23 +00008359 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008360 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008361 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362 // If we do not have to emit the truncate + sext pair, then it's always
8363 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008364 //
8365 // It's not safe to eliminate the trunc + sext pair if one of the
8366 // eliminated cast is a truncate. e.g.
8367 // t2 = trunc i32 t1 to i16
8368 // t3 = sext i16 t2 to i32
8369 // !=
8370 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008371 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008372 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8373 if (NumSignBits > (DestBitSize - SrcBitSize))
8374 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008375
8376 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008377 if (TryI->use_empty())
8378 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008379 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008380 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 }
Evan Chengf35fd542009-01-15 17:01:23 +00008382 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008383
8384 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008385 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8386 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008387 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8388 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008389 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008390 // Just replace this cast with the result.
8391 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008392
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 assert(Res->getType() == DestTy);
8394 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008395 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008396 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 // Just replace this cast with the result.
8398 return ReplaceInstUsesWith(CI, Res);
8399 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008400 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008401
8402 // If the high bits are already zero, just replace this cast with the
8403 // result.
8404 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8405 if (MaskedValueIsZero(Res, Mask))
8406 return ReplaceInstUsesWith(CI, Res);
8407
8408 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008409 Constant *C = ConstantInt::get(*Context,
8410 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008411 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008412 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008413 case Instruction::SExt: {
8414 // If the high bits are already filled with sign bit, just replace this
8415 // cast with the result.
8416 unsigned NumSignBits = ComputeNumSignBits(Res);
8417 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008418 return ReplaceInstUsesWith(CI, Res);
8419
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008421 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008422 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8423 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008424 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008425 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008426 }
8427 }
8428
8429 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8430 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8431
8432 switch (SrcI->getOpcode()) {
8433 case Instruction::Add:
8434 case Instruction::Mul:
8435 case Instruction::And:
8436 case Instruction::Or:
8437 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008438 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008439 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8440 // Don't insert two casts unless at least one can be eliminated.
8441 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008442 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008443 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8444 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008445 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008446 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008447 }
8448 }
8449
8450 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8451 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8452 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb3056fa2009-07-21 18:03:38 +00008453 Op1 == Context->getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008454 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008455 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008456 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008457 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008458 }
8459 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008460
Eli Friedman65445c52009-07-13 21:45:57 +00008461 case Instruction::Shl: {
8462 // Canonicalize trunc inside shl, if we can.
8463 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8464 if (CI && DestBitSize < SrcBitSize &&
8465 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8466 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8467 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008468 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008469 }
8470 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008471 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008472 }
8473 return 0;
8474}
8475
Chris Lattner8a9f5712007-04-11 06:57:46 +00008476Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008477 if (Instruction *Result = commonIntCastTransforms(CI))
8478 return Result;
8479
8480 Value *Src = CI.getOperand(0);
8481 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008482 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8483 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008484
8485 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008486 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008487 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008488 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008489 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008490 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008491 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008492
Chris Lattner4f9797d2009-03-24 18:15:30 +00008493 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8494 ConstantInt *ShAmtV = 0;
8495 Value *ShiftOp = 0;
8496 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008497 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008498 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8499
8500 // Get a mask for the bits shifting in.
8501 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8502 if (MaskedValueIsZero(ShiftOp, Mask)) {
8503 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008504 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008505
8506 // Okay, we can shrink this. Truncate the input, then return a new
8507 // shift.
8508 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008509 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008510 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008511 }
8512 }
8513
8514 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008515}
8516
Evan Chengb98a10e2008-03-24 00:21:34 +00008517/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8518/// in order to eliminate the icmp.
8519Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8520 bool DoXform) {
8521 // If we are just checking for a icmp eq of a single bit and zext'ing it
8522 // to an integer, then shift the bit to the appropriate place and then
8523 // cast to integer to avoid the comparison.
8524 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8525 const APInt &Op1CV = Op1C->getValue();
8526
8527 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8528 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8529 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8530 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8531 if (!DoXform) return ICI;
8532
8533 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008534 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008535 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008536 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008537 In->getName()+".lobit"),
8538 CI);
8539 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008540 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008541 false/*ZExt*/, "tmp", &CI);
8542
8543 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008544 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008545 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008546 In->getName()+".not"),
8547 CI);
8548 }
8549
8550 return ReplaceInstUsesWith(CI, In);
8551 }
8552
8553
8554
8555 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8556 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8557 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8558 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8559 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8560 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8561 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8562 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8563 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8564 // This only works for EQ and NE
8565 ICI->isEquality()) {
8566 // If Op1C some other power of two, convert:
8567 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8568 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8569 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8570 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8571
8572 APInt KnownZeroMask(~KnownZero);
8573 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8574 if (!DoXform) return ICI;
8575
8576 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8577 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8578 // (X&4) == 2 --> false
8579 // (X&4) != 2 --> true
Owen Andersoneed707b2009-07-24 23:12:02 +00008580 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Andersond672ecb2009-07-03 00:17:18 +00008581 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008582 return ReplaceInstUsesWith(CI, Res);
8583 }
8584
8585 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8586 Value *In = ICI->getOperand(0);
8587 if (ShiftAmt) {
8588 // Perform a logical shr by shiftamt.
8589 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008590 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008591 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008592 In->getName()+".lobit"), CI);
8593 }
8594
8595 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008596 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008597 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008598 InsertNewInstBefore(cast<Instruction>(In), CI);
8599 }
8600
8601 if (CI.getType() == In->getType())
8602 return ReplaceInstUsesWith(CI, In);
8603 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008604 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008605 }
8606 }
8607 }
8608
8609 return 0;
8610}
8611
Chris Lattner8a9f5712007-04-11 06:57:46 +00008612Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008613 // If one of the common conversion will work ..
8614 if (Instruction *Result = commonIntCastTransforms(CI))
8615 return Result;
8616
8617 Value *Src = CI.getOperand(0);
8618
Chris Lattnera84f47c2009-02-17 20:47:23 +00008619 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8620 // types and if the sizes are just right we can convert this into a logical
8621 // 'and' which will be much cheaper than the pair of casts.
8622 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8623 // Get the sizes of the types involved. We know that the intermediate type
8624 // will be smaller than A or C, but don't know the relation between A and C.
8625 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008626 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8627 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8628 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008629 // If we're actually extending zero bits, then if
8630 // SrcSize < DstSize: zext(a & mask)
8631 // SrcSize == DstSize: a & mask
8632 // SrcSize > DstSize: trunc(a) & mask
8633 if (SrcSize < DstSize) {
8634 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008635 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008636 Instruction *And =
8637 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8638 InsertNewInstBefore(And, CI);
8639 return new ZExtInst(And, CI.getType());
8640 } else if (SrcSize == DstSize) {
8641 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008642 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008643 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008644 } else if (SrcSize > DstSize) {
8645 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8646 InsertNewInstBefore(Trunc, CI);
8647 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008648 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008649 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008650 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008651 }
8652 }
8653
Evan Chengb98a10e2008-03-24 00:21:34 +00008654 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8655 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008656
Evan Chengb98a10e2008-03-24 00:21:34 +00008657 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8658 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8659 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8660 // of the (zext icmp) will be transformed.
8661 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8662 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8663 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8664 (transformZExtICmp(LHS, CI, false) ||
8665 transformZExtICmp(RHS, CI, false))) {
8666 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8667 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008668 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008669 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008670 }
8671
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008672 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008673 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8674 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8675 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8676 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008677 if (TI0->getType() == CI.getType())
8678 return
8679 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008680 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008681 }
8682
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008683 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8684 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8685 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8686 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8687 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8688 And->getOperand(1) == C)
8689 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8690 Value *TI0 = TI->getOperand(0);
8691 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008692 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008693 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8694 InsertNewInstBefore(NewAnd, *And);
8695 return BinaryOperator::CreateXor(NewAnd, ZC);
8696 }
8697 }
8698
Reid Spencer3da59db2006-11-27 01:05:10 +00008699 return 0;
8700}
8701
Chris Lattner8a9f5712007-04-11 06:57:46 +00008702Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008703 if (Instruction *I = commonIntCastTransforms(CI))
8704 return I;
8705
Chris Lattner8a9f5712007-04-11 06:57:46 +00008706 Value *Src = CI.getOperand(0);
8707
Dan Gohman1975d032008-10-30 20:40:10 +00008708 // Canonicalize sign-extend from i1 to a select.
8709 if (Src->getType() == Type::Int1Ty)
8710 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008711 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008712 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008713
8714 // See if the value being truncated is already sign extended. If so, just
8715 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008716 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008717 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008718 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8719 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8720 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008721 unsigned NumSignBits = ComputeNumSignBits(Op);
8722
8723 if (OpBits == DestBits) {
8724 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8725 // bits, it is already ready.
8726 if (NumSignBits > DestBits-MidBits)
8727 return ReplaceInstUsesWith(CI, Op);
8728 } else if (OpBits < DestBits) {
8729 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8730 // bits, just sext from i32.
8731 if (NumSignBits > OpBits-MidBits)
8732 return new SExtInst(Op, CI.getType(), "tmp");
8733 } else {
8734 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8735 // bits, just truncate to i32.
8736 if (NumSignBits > OpBits-MidBits)
8737 return new TruncInst(Op, CI.getType(), "tmp");
8738 }
8739 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008740
8741 // If the input is a shl/ashr pair of a same constant, then this is a sign
8742 // extension from a smaller value. If we could trust arbitrary bitwidth
8743 // integers, we could turn this into a truncate to the smaller bit and then
8744 // use a sext for the whole extension. Since we don't, look deeper and check
8745 // for a truncate. If the source and dest are the same type, eliminate the
8746 // trunc and extend and just do shifts. For example, turn:
8747 // %a = trunc i32 %i to i8
8748 // %b = shl i8 %a, 6
8749 // %c = ashr i8 %b, 6
8750 // %d = sext i8 %c to i32
8751 // into:
8752 // %a = shl i32 %i, 30
8753 // %d = ashr i32 %a, 30
8754 Value *A = 0;
8755 ConstantInt *BA = 0, *CA = 0;
8756 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008757 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008758 BA == CA && isa<TruncInst>(A)) {
8759 Value *I = cast<TruncInst>(A)->getOperand(0);
8760 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008761 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8762 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008763 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008764 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008765 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8766 CI.getName()), CI);
8767 return BinaryOperator::CreateAShr(I, ShAmtV);
8768 }
8769 }
8770
Chris Lattnerba417832007-04-11 06:12:58 +00008771 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008772}
8773
Chris Lattnerb7530652008-01-27 05:29:54 +00008774/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8775/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008776static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008777 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008778 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008779 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008780 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8781 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008782 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008783 return 0;
8784}
8785
8786/// LookThroughFPExtensions - If this is an fp extension instruction, look
8787/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008788static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008789 if (Instruction *I = dyn_cast<Instruction>(V))
8790 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008791 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008792
8793 // If this value is a constant, return the constant in the smallest FP type
8794 // that can accurately represent it. This allows us to turn
8795 // (float)((double)X+2.0) into x+2.0f.
8796 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8797 if (CFP->getType() == Type::PPC_FP128Ty)
8798 return V; // No constant folding of this.
8799 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008800 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008801 return V;
8802 if (CFP->getType() == Type::DoubleTy)
8803 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008804 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008805 return V;
8806 // Don't try to shrink to various long double types.
8807 }
8808
8809 return V;
8810}
8811
8812Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8813 if (Instruction *I = commonCastTransforms(CI))
8814 return I;
8815
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008816 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008817 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008818 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008819 // many builtins (sqrt, etc).
8820 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8821 if (OpI && OpI->hasOneUse()) {
8822 switch (OpI->getOpcode()) {
8823 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008824 case Instruction::FAdd:
8825 case Instruction::FSub:
8826 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008827 case Instruction::FDiv:
8828 case Instruction::FRem:
8829 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008830 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8831 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008832 if (LHSTrunc->getType() != SrcTy &&
8833 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008834 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008835 // If the source types were both smaller than the destination type of
8836 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008837 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8838 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008839 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8840 CI.getType(), CI);
8841 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8842 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008843 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008844 }
8845 }
8846 break;
8847 }
8848 }
8849 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008850}
8851
8852Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8853 return commonCastTransforms(CI);
8854}
8855
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008856Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008857 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8858 if (OpI == 0)
8859 return commonCastTransforms(FI);
8860
8861 // fptoui(uitofp(X)) --> X
8862 // fptoui(sitofp(X)) --> X
8863 // This is safe if the intermediate type has enough bits in its mantissa to
8864 // accurately represent all values of X. For example, do not do this with
8865 // i64->float->i64. This is also safe for sitofp case, because any negative
8866 // 'X' value would cause an undefined result for the fptoui.
8867 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8868 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008869 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008870 OpI->getType()->getFPMantissaWidth())
8871 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008872
8873 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008874}
8875
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008876Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008877 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8878 if (OpI == 0)
8879 return commonCastTransforms(FI);
8880
8881 // fptosi(sitofp(X)) --> X
8882 // fptosi(uitofp(X)) --> X
8883 // This is safe if the intermediate type has enough bits in its mantissa to
8884 // accurately represent all values of X. For example, do not do this with
8885 // i64->float->i64. This is also safe for sitofp case, because any negative
8886 // 'X' value would cause an undefined result for the fptoui.
8887 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8888 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008889 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008890 OpI->getType()->getFPMantissaWidth())
8891 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008892
8893 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008894}
8895
8896Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8897 return commonCastTransforms(CI);
8898}
8899
8900Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8901 return commonCastTransforms(CI);
8902}
8903
Chris Lattnera0e69692009-03-24 18:35:40 +00008904Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8905 // If the destination integer type is smaller than the intptr_t type for
8906 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8907 // trunc to be exposed to other transforms. Don't do this for extending
8908 // ptrtoint's, because we don't know if the target sign or zero extends its
8909 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008910 if (TD &&
8911 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008912 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8913 TD->getIntPtrType(),
8914 "tmp"), CI);
8915 return new TruncInst(P, CI.getType());
8916 }
8917
Chris Lattnerd3e28342007-04-27 17:44:50 +00008918 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008919}
8920
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008921Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008922 // If the source integer type is larger than the intptr_t type for
8923 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8924 // allows the trunc to be exposed to other transforms. Don't do this for
8925 // extending inttoptr's, because we don't know if the target sign or zero
8926 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008927 if (TD &&
8928 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008929 TD->getPointerSizeInBits()) {
8930 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8931 TD->getIntPtrType(),
8932 "tmp"), CI);
8933 return new IntToPtrInst(P, CI.getType());
8934 }
8935
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008936 if (Instruction *I = commonCastTransforms(CI))
8937 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008938
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008939 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008940}
8941
Chris Lattnerd3e28342007-04-27 17:44:50 +00008942Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008943 // If the operands are integer typed then apply the integer transforms,
8944 // otherwise just apply the common ones.
8945 Value *Src = CI.getOperand(0);
8946 const Type *SrcTy = Src->getType();
8947 const Type *DestTy = CI.getType();
8948
Eli Friedman7e25d452009-07-13 20:53:00 +00008949 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008950 if (Instruction *I = commonPointerCastTransforms(CI))
8951 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008952 } else {
8953 if (Instruction *Result = commonCastTransforms(CI))
8954 return Result;
8955 }
8956
8957
8958 // Get rid of casts from one type to the same type. These are useless and can
8959 // be replaced by the operand.
8960 if (DestTy == Src->getType())
8961 return ReplaceInstUsesWith(CI, Src);
8962
Reid Spencer3da59db2006-11-27 01:05:10 +00008963 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008964 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8965 const Type *DstElTy = DstPTy->getElementType();
8966 const Type *SrcElTy = SrcPTy->getElementType();
8967
Nate Begeman83ad90a2008-03-31 00:22:16 +00008968 // If the address spaces don't match, don't eliminate the bitcast, which is
8969 // required for changing types.
8970 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8971 return 0;
8972
Chris Lattnerd3e28342007-04-27 17:44:50 +00008973 // If we are casting a malloc or alloca to a pointer to a type of the same
8974 // size, rewrite the allocation instruction to allocate the "right" type.
8975 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8976 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8977 return V;
8978
Chris Lattnerd717c182007-05-05 22:32:24 +00008979 // If the source and destination are pointers, and this cast is equivalent
8980 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008981 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00008982 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008983 unsigned NumZeros = 0;
8984 while (SrcElTy != DstElTy &&
8985 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8986 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8987 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8988 ++NumZeros;
8989 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008990
Chris Lattnerd3e28342007-04-27 17:44:50 +00008991 // If we found a path from the src to dest, create the getelementptr now.
8992 if (SrcElTy == DstElTy) {
8993 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008994 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8995 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008996 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008997 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008998
Eli Friedman2451a642009-07-18 23:06:53 +00008999 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9000 if (DestVTy->getNumElements() == 1) {
9001 if (!isa<VectorType>(SrcTy)) {
9002 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9003 DestVTy->getElementType(), CI);
9004 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
9005 Context->getNullValue(Type::Int32Ty));
9006 }
9007 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9008 }
9009 }
9010
9011 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9012 if (SrcVTy->getNumElements() == 1) {
9013 if (!isa<VectorType>(DestTy)) {
9014 Instruction *Elem =
Eric Christophera3500da2009-07-25 02:28:41 +00009015 ExtractElementInst::Create(Src, Context->getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00009016 InsertNewInstBefore(Elem, CI);
9017 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9018 }
9019 }
9020 }
9021
Reid Spencer3da59db2006-11-27 01:05:10 +00009022 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9023 if (SVI->hasOneUse()) {
9024 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9025 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009026 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009027 cast<VectorType>(DestTy)->getNumElements() ==
9028 SVI->getType()->getNumElements() &&
9029 SVI->getType()->getNumElements() ==
9030 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 CastInst *Tmp;
9032 // If either of the operands is a cast from CI.getType(), then
9033 // evaluating the shuffle in the casted destination's type will allow
9034 // us to eliminate at least one cast.
9035 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9036 Tmp->getOperand(0)->getType() == DestTy) ||
9037 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9038 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009039 Value *LHS = InsertCastBefore(Instruction::BitCast,
9040 SVI->getOperand(0), DestTy, CI);
9041 Value *RHS = InsertCastBefore(Instruction::BitCast,
9042 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009043 // Return a new shuffle vector. Use the same element ID's, as we
9044 // know the vector types match #elts.
9045 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009046 }
9047 }
9048 }
9049 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009050 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009051}
9052
Chris Lattnere576b912004-04-09 23:46:01 +00009053/// GetSelectFoldableOperands - We want to turn code that looks like this:
9054/// %C = or %A, %B
9055/// %D = select %cond, %C, %A
9056/// into:
9057/// %C = select %cond, %B, 0
9058/// %D = or %A, %C
9059///
9060/// Assuming that the specified instruction is an operand to the select, return
9061/// a bitmask indicating which operands of this instruction are foldable if they
9062/// equal the other incoming value of the select.
9063///
9064static unsigned GetSelectFoldableOperands(Instruction *I) {
9065 switch (I->getOpcode()) {
9066 case Instruction::Add:
9067 case Instruction::Mul:
9068 case Instruction::And:
9069 case Instruction::Or:
9070 case Instruction::Xor:
9071 return 3; // Can fold through either operand.
9072 case Instruction::Sub: // Can only fold on the amount subtracted.
9073 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009074 case Instruction::LShr:
9075 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009076 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009077 default:
9078 return 0; // Cannot fold
9079 }
9080}
9081
9082/// GetSelectFoldableConstant - For the same transformation as the previous
9083/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009084static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009085 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009086 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009087 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009088 case Instruction::Add:
9089 case Instruction::Sub:
9090 case Instruction::Or:
9091 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009092 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009093 case Instruction::LShr:
9094 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009095 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009096 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009097 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009098 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009099 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009100 }
9101}
9102
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009103/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9104/// have the same opcode and only one use each. Try to simplify this.
9105Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9106 Instruction *FI) {
9107 if (TI->getNumOperands() == 1) {
9108 // If this is a non-volatile load or a cast from the same type,
9109 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009110 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009111 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9112 return 0;
9113 } else {
9114 return 0; // unknown unary op.
9115 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009116
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009117 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009118 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009119 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009120 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009121 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009122 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 }
9124
Reid Spencer832254e2007-02-02 02:16:23 +00009125 // Only handle binary operators here.
9126 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009127 return 0;
9128
9129 // Figure out if the operations have any operands in common.
9130 Value *MatchOp, *OtherOpT, *OtherOpF;
9131 bool MatchIsOpZero;
9132 if (TI->getOperand(0) == FI->getOperand(0)) {
9133 MatchOp = TI->getOperand(0);
9134 OtherOpT = TI->getOperand(1);
9135 OtherOpF = FI->getOperand(1);
9136 MatchIsOpZero = true;
9137 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9138 MatchOp = TI->getOperand(1);
9139 OtherOpT = TI->getOperand(0);
9140 OtherOpF = FI->getOperand(0);
9141 MatchIsOpZero = false;
9142 } else if (!TI->isCommutative()) {
9143 return 0;
9144 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9145 MatchOp = TI->getOperand(0);
9146 OtherOpT = TI->getOperand(1);
9147 OtherOpF = FI->getOperand(0);
9148 MatchIsOpZero = true;
9149 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9150 MatchOp = TI->getOperand(1);
9151 OtherOpT = TI->getOperand(0);
9152 OtherOpF = FI->getOperand(1);
9153 MatchIsOpZero = true;
9154 } else {
9155 return 0;
9156 }
9157
9158 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009159 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9160 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009161 InsertNewInstBefore(NewSI, SI);
9162
9163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9164 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009165 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009166 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009167 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009168 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009169 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009170 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009171}
9172
Evan Chengde621922009-03-31 20:42:45 +00009173static bool isSelect01(Constant *C1, Constant *C2) {
9174 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9175 if (!C1I)
9176 return false;
9177 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9178 if (!C2I)
9179 return false;
9180 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9181}
9182
9183/// FoldSelectIntoOp - Try fold the select into one of the operands to
9184/// facilitate further optimization.
9185Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9186 Value *FalseVal) {
9187 // See the comment above GetSelectFoldableOperands for a description of the
9188 // transformation we are doing here.
9189 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9190 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9191 !isa<Constant>(FalseVal)) {
9192 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9193 unsigned OpToFold = 0;
9194 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9195 OpToFold = 1;
9196 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9197 OpToFold = 2;
9198 }
9199
9200 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009201 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009202 Value *OOp = TVI->getOperand(2-OpToFold);
9203 // Avoid creating select between 2 constants unless it's selecting
9204 // between 0 and 1.
9205 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9206 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9207 InsertNewInstBefore(NewSel, SI);
9208 NewSel->takeName(TVI);
9209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9210 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009211 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009212 }
9213 }
9214 }
9215 }
9216 }
9217
9218 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9219 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9220 !isa<Constant>(TrueVal)) {
9221 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9222 unsigned OpToFold = 0;
9223 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9224 OpToFold = 1;
9225 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9226 OpToFold = 2;
9227 }
9228
9229 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009230 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009231 Value *OOp = FVI->getOperand(2-OpToFold);
9232 // Avoid creating select between 2 constants unless it's selecting
9233 // between 0 and 1.
9234 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9235 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9236 InsertNewInstBefore(NewSel, SI);
9237 NewSel->takeName(FVI);
9238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9239 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009240 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009241 }
9242 }
9243 }
9244 }
9245 }
9246
9247 return 0;
9248}
9249
Dan Gohman81b28ce2008-09-16 18:46:06 +00009250/// visitSelectInstWithICmp - Visit a SelectInst that has an
9251/// ICmpInst as its first operand.
9252///
9253Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9254 ICmpInst *ICI) {
9255 bool Changed = false;
9256 ICmpInst::Predicate Pred = ICI->getPredicate();
9257 Value *CmpLHS = ICI->getOperand(0);
9258 Value *CmpRHS = ICI->getOperand(1);
9259 Value *TrueVal = SI.getTrueValue();
9260 Value *FalseVal = SI.getFalseValue();
9261
9262 // Check cases where the comparison is with a constant that
9263 // can be adjusted to fit the min/max idiom. We may edit ICI in
9264 // place here, so make sure the select is the only user.
9265 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009266 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009267 switch (Pred) {
9268 default: break;
9269 case ICmpInst::ICMP_ULT:
9270 case ICmpInst::ICMP_SLT: {
9271 // X < MIN ? T : F --> F
9272 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9273 return ReplaceInstUsesWith(SI, FalseVal);
9274 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009275 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009276 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9277 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9278 Pred = ICmpInst::getSwappedPredicate(Pred);
9279 CmpRHS = AdjustedRHS;
9280 std::swap(FalseVal, TrueVal);
9281 ICI->setPredicate(Pred);
9282 ICI->setOperand(1, CmpRHS);
9283 SI.setOperand(1, TrueVal);
9284 SI.setOperand(2, FalseVal);
9285 Changed = true;
9286 }
9287 break;
9288 }
9289 case ICmpInst::ICMP_UGT:
9290 case ICmpInst::ICMP_SGT: {
9291 // X > MAX ? T : F --> F
9292 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9293 return ReplaceInstUsesWith(SI, FalseVal);
9294 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009295 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009296 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9297 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9298 Pred = ICmpInst::getSwappedPredicate(Pred);
9299 CmpRHS = AdjustedRHS;
9300 std::swap(FalseVal, TrueVal);
9301 ICI->setPredicate(Pred);
9302 ICI->setOperand(1, CmpRHS);
9303 SI.setOperand(1, TrueVal);
9304 SI.setOperand(2, FalseVal);
9305 Changed = true;
9306 }
9307 break;
9308 }
9309 }
9310
Dan Gohman1975d032008-10-30 20:40:10 +00009311 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9312 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009313 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009314 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9315 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009316 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009317 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9318 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009319 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9320
Dan Gohman1975d032008-10-30 20:40:10 +00009321 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9322 // If we are just checking for a icmp eq of a single bit and zext'ing it
9323 // to an integer, then shift the bit to the appropriate place and then
9324 // cast to integer to avoid the comparison.
9325 const APInt &Op1CV = CI->getValue();
9326
9327 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9328 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9329 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009330 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009331 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009332 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009333 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009334 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009335 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009336 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009337 if (In->getType() != SI.getType())
9338 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009339 true/*SExt*/, "tmp", ICI);
9340
9341 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009342 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009343 In->getName()+".not"), *ICI);
9344
9345 return ReplaceInstUsesWith(SI, In);
9346 }
9347 }
9348 }
9349
Dan Gohman81b28ce2008-09-16 18:46:06 +00009350 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9351 // Transform (X == Y) ? X : Y -> Y
9352 if (Pred == ICmpInst::ICMP_EQ)
9353 return ReplaceInstUsesWith(SI, FalseVal);
9354 // Transform (X != Y) ? X : Y -> X
9355 if (Pred == ICmpInst::ICMP_NE)
9356 return ReplaceInstUsesWith(SI, TrueVal);
9357 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9358
9359 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9360 // Transform (X == Y) ? Y : X -> X
9361 if (Pred == ICmpInst::ICMP_EQ)
9362 return ReplaceInstUsesWith(SI, FalseVal);
9363 // Transform (X != Y) ? Y : X -> Y
9364 if (Pred == ICmpInst::ICMP_NE)
9365 return ReplaceInstUsesWith(SI, TrueVal);
9366 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9367 }
9368
9369 /// NOTE: if we wanted to, this is where to detect integer ABS
9370
9371 return Changed ? &SI : 0;
9372}
9373
Chris Lattner3d69f462004-03-12 05:52:32 +00009374Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009375 Value *CondVal = SI.getCondition();
9376 Value *TrueVal = SI.getTrueValue();
9377 Value *FalseVal = SI.getFalseValue();
9378
9379 // select true, X, Y -> X
9380 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009381 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009382 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009383
9384 // select C, X, X -> X
9385 if (TrueVal == FalseVal)
9386 return ReplaceInstUsesWith(SI, TrueVal);
9387
Chris Lattnere87597f2004-10-16 18:11:37 +00009388 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9389 return ReplaceInstUsesWith(SI, FalseVal);
9390 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9391 return ReplaceInstUsesWith(SI, TrueVal);
9392 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9393 if (isa<Constant>(TrueVal))
9394 return ReplaceInstUsesWith(SI, TrueVal);
9395 else
9396 return ReplaceInstUsesWith(SI, FalseVal);
9397 }
9398
Reid Spencer4fe16d62007-01-11 18:21:29 +00009399 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009400 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009401 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009402 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009403 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009404 } else {
9405 // Change: A = select B, false, C --> A = and !B, C
9406 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009407 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009408 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009409 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009410 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009411 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009412 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009413 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009414 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009415 } else {
9416 // Change: A = select B, C, true --> A = or !B, C
9417 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009418 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009419 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009420 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009421 }
9422 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009423
9424 // select a, b, a -> a&b
9425 // select a, a, b -> a|b
9426 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009427 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009428 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009429 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009430 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009431
Chris Lattner2eefe512004-04-09 19:05:30 +00009432 // Selecting between two integer constants?
9433 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9434 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009435 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009436 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009438 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009439 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009440 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009441 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009442 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009443 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009444 }
Chris Lattner457dd822004-06-09 07:59:58 +00009445
Reid Spencere4d87aa2006-12-23 06:05:41 +00009446 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009447 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009448 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009449 // non-constant value, eliminate this whole mess. This corresponds to
9450 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009451 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009452 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009453 cast<Constant>(IC->getOperand(1))->isNullValue())
9454 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9455 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009456 isa<ConstantInt>(ICA->getOperand(1)) &&
9457 (ICA->getOperand(1) == TrueValC ||
9458 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009459 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9460 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009461 // know whether we have a icmp_ne or icmp_eq and whether the
9462 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009463 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009464 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009465 Value *V = ICA;
9466 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009467 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009468 Instruction::Xor, V, ICA->getOperand(1)), SI);
9469 return ReplaceInstUsesWith(SI, V);
9470 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009471 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009472 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009473
9474 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9476 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009477 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009478 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9479 // This is not safe in general for floating point:
9480 // consider X== -0, Y== +0.
9481 // It becomes safe if either operand is a nonzero constant.
9482 ConstantFP *CFPt, *CFPf;
9483 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9484 !CFPt->getValueAPF().isZero()) ||
9485 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9486 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009487 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009488 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009489 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009490 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009491 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009492 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009493
Reid Spencere4d87aa2006-12-23 06:05:41 +00009494 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009495 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009496 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9497 // This is not safe in general for floating point:
9498 // consider X== -0, Y== +0.
9499 // It becomes safe if either operand is a nonzero constant.
9500 ConstantFP *CFPt, *CFPf;
9501 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9502 !CFPt->getValueAPF().isZero()) ||
9503 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9504 !CFPf->getValueAPF().isZero()))
9505 return ReplaceInstUsesWith(SI, FalseVal);
9506 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009507 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009508 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9509 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009510 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009511 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009512 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009513 }
9514
9515 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009516 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9517 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9518 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009519
Chris Lattner87875da2005-01-13 22:52:24 +00009520 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9521 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9522 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009523 Instruction *AddOp = 0, *SubOp = 0;
9524
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009525 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9526 if (TI->getOpcode() == FI->getOpcode())
9527 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9528 return IV;
9529
9530 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9531 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009532 if ((TI->getOpcode() == Instruction::Sub &&
9533 FI->getOpcode() == Instruction::Add) ||
9534 (TI->getOpcode() == Instruction::FSub &&
9535 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009536 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009537 } else if ((FI->getOpcode() == Instruction::Sub &&
9538 TI->getOpcode() == Instruction::Add) ||
9539 (FI->getOpcode() == Instruction::FSub &&
9540 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009541 AddOp = TI; SubOp = FI;
9542 }
9543
9544 if (AddOp) {
9545 Value *OtherAddOp = 0;
9546 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9547 OtherAddOp = AddOp->getOperand(1);
9548 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9549 OtherAddOp = AddOp->getOperand(0);
9550 }
9551
9552 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009553 // So at this point we know we have (Y -> OtherAddOp):
9554 // select C, (add X, Y), (sub X, Z)
9555 Value *NegVal; // Compute -Z
9556 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009557 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009558 } else {
9559 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009560 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9561 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009562 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009563
9564 Value *NewTrueOp = OtherAddOp;
9565 Value *NewFalseOp = NegVal;
9566 if (AddOp != TI)
9567 std::swap(NewTrueOp, NewFalseOp);
9568 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009569 SelectInst::Create(CondVal, NewTrueOp,
9570 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009571
9572 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009573 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009574 }
9575 }
9576 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009577
Chris Lattnere576b912004-04-09 23:46:01 +00009578 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009579 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009580 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9581 if (FoldI)
9582 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009583 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009584
9585 if (BinaryOperator::isNot(CondVal)) {
9586 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9587 SI.setOperand(1, FalseVal);
9588 SI.setOperand(2, TrueVal);
9589 return &SI;
9590 }
9591
Chris Lattner3d69f462004-03-12 05:52:32 +00009592 return 0;
9593}
9594
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595/// EnforceKnownAlignment - If the specified pointer points to an object that
9596/// we control, modify the object's alignment to PrefAlign. This isn't
9597/// often possible though. If alignment is important, a more reliable approach
9598/// is to simply align all global variables and allocation instructions to
9599/// their preferred alignment from the beginning.
9600///
9601static unsigned EnforceKnownAlignment(Value *V,
9602 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009603
Dan Gohmaneee962e2008-04-10 18:43:06 +00009604 User *U = dyn_cast<User>(V);
9605 if (!U) return Align;
9606
Dan Gohmanca178902009-07-17 20:47:02 +00009607 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009608 default: break;
9609 case Instruction::BitCast:
9610 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9611 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009612 // If all indexes are zero, it is just the alignment of the base pointer.
9613 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009614 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009615 if (!isa<Constant>(*i) ||
9616 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009617 AllZeroOperands = false;
9618 break;
9619 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009620
9621 if (AllZeroOperands) {
9622 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009624 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009625 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009626 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009627 }
9628
9629 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9630 // If there is a large requested alignment and we can, bump up the alignment
9631 // of the global.
9632 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009633 if (GV->getAlignment() >= PrefAlign)
9634 Align = GV->getAlignment();
9635 else {
9636 GV->setAlignment(PrefAlign);
9637 Align = PrefAlign;
9638 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009639 }
9640 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9641 // If there is a requested alignment and if this is an alloca, round up. We
9642 // don't do this for malloc, because some systems can't respect the request.
9643 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009644 if (AI->getAlignment() >= PrefAlign)
9645 Align = AI->getAlignment();
9646 else {
9647 AI->setAlignment(PrefAlign);
9648 Align = PrefAlign;
9649 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009650 }
9651 }
9652
9653 return Align;
9654}
9655
9656/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9657/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9658/// and it is more than the alignment of the ultimate object, see if we can
9659/// increase the alignment of the ultimate object, making this check succeed.
9660unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9661 unsigned PrefAlign) {
9662 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9663 sizeof(PrefAlign) * CHAR_BIT;
9664 APInt Mask = APInt::getAllOnesValue(BitWidth);
9665 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9666 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9667 unsigned TrailZ = KnownZero.countTrailingOnes();
9668 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9669
9670 if (PrefAlign > Align)
9671 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9672
9673 // We don't need to make any adjustment.
9674 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009675}
9676
Chris Lattnerf497b022008-01-13 23:50:23 +00009677Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009678 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009679 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009680 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009681 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009682
9683 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009684 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009685 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009686 return MI;
9687 }
9688
9689 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9690 // load/store.
9691 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9692 if (MemOpLength == 0) return 0;
9693
Chris Lattner37ac6082008-01-14 00:28:35 +00009694 // Source and destination pointer types are always "i8*" for intrinsic. See
9695 // if the size is something we can handle with a single primitive load/store.
9696 // A single load+store correctly handles overlapping memory in the memmove
9697 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009698 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009699 if (Size == 0) return MI; // Delete this mem transfer.
9700
9701 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009702 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009703
Chris Lattner37ac6082008-01-14 00:28:35 +00009704 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009705 Type *NewPtrTy =
9706 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009707
9708 // Memcpy forces the use of i8* for the source and destination. That means
9709 // that if you're using memcpy to move one double around, you'll get a cast
9710 // from double* to i8*. We'd much rather use a double load+store rather than
9711 // an i64 load+store, here because this improves the odds that the source or
9712 // dest address will be promotable. See if we can find a better type than the
9713 // integer datatype.
9714 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9715 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009716 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009717 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9718 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009719 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009720 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9721 if (STy->getNumElements() == 1)
9722 SrcETy = STy->getElementType(0);
9723 else
9724 break;
9725 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9726 if (ATy->getNumElements() == 1)
9727 SrcETy = ATy->getElementType();
9728 else
9729 break;
9730 } else
9731 break;
9732 }
9733
Dan Gohman8f8e2692008-05-23 01:52:21 +00009734 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009735 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009736 }
9737 }
9738
9739
Chris Lattnerf497b022008-01-13 23:50:23 +00009740 // If the memcpy/memmove provides better alignment info than we can
9741 // infer, use it.
9742 SrcAlign = std::max(SrcAlign, CopyAlign);
9743 DstAlign = std::max(DstAlign, CopyAlign);
9744
9745 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9746 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009747 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9748 InsertNewInstBefore(L, *MI);
9749 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9750
9751 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009752 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009753 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009754}
Chris Lattner3d69f462004-03-12 05:52:32 +00009755
Chris Lattner69ea9d22008-04-30 06:39:11 +00009756Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9757 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009758 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009759 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009760 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009761 return MI;
9762 }
9763
9764 // Extract the length and alignment and fill if they are constant.
9765 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9766 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9767 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9768 return 0;
9769 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009770 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009771
9772 // If the length is zero, this is a no-op
9773 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9774
9775 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9776 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009777 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009778
9779 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009780 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009781
9782 // Alignment 0 is identity for alignment 1 for memset, but not store.
9783 if (Alignment == 0) Alignment = 1;
9784
9785 // Extract the fill value and store.
9786 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009787 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009788 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009789
9790 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009791 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009792 return MI;
9793 }
9794
9795 return 0;
9796}
9797
9798
Chris Lattner8b0ea312006-01-13 20:11:04 +00009799/// visitCallInst - CallInst simplification. This mostly only handles folding
9800/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9801/// the heavy lifting.
9802///
Chris Lattner9fe38862003-06-19 17:00:31 +00009803Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009804 // If the caller function is nounwind, mark the call as nounwind, even if the
9805 // callee isn't.
9806 if (CI.getParent()->getParent()->doesNotThrow() &&
9807 !CI.doesNotThrow()) {
9808 CI.setDoesNotThrow();
9809 return &CI;
9810 }
9811
9812
9813
Chris Lattner8b0ea312006-01-13 20:11:04 +00009814 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9815 if (!II) return visitCallSite(&CI);
9816
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009817 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9818 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009819 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009820 bool Changed = false;
9821
9822 // memmove/cpy/set of zero bytes is a noop.
9823 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9824 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9825
Chris Lattner35b9e482004-10-12 04:52:52 +00009826 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009827 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009828 // Replace the instruction with just byte operations. We would
9829 // transform other cases to loads/stores, but we don't know if
9830 // alignment is sufficient.
9831 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009832 }
9833
Chris Lattner35b9e482004-10-12 04:52:52 +00009834 // If we have a memmove and the source operation is a constant global,
9835 // then the source and dest pointers can't alias, so we can change this
9836 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009837 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009838 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9839 if (GVSrc->isConstant()) {
9840 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009841 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9842 const Type *Tys[1];
9843 Tys[0] = CI.getOperand(3)->getType();
9844 CI.setOperand(0,
9845 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009846 Changed = true;
9847 }
Chris Lattnera935db82008-05-28 05:30:41 +00009848
9849 // memmove(x,x,size) -> noop.
9850 if (MMI->getSource() == MMI->getDest())
9851 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009852 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009853
Chris Lattner95a959d2006-03-06 20:18:44 +00009854 // If we can determine a pointer alignment that is bigger than currently
9855 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009856 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009857 if (Instruction *I = SimplifyMemTransfer(MI))
9858 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009859 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9860 if (Instruction *I = SimplifyMemSet(MSI))
9861 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009862 }
9863
Chris Lattner8b0ea312006-01-13 20:11:04 +00009864 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009865 }
9866
9867 switch (II->getIntrinsicID()) {
9868 default: break;
9869 case Intrinsic::bswap:
9870 // bswap(bswap(x)) -> x
9871 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9872 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9873 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9874 break;
9875 case Intrinsic::ppc_altivec_lvx:
9876 case Intrinsic::ppc_altivec_lvxl:
9877 case Intrinsic::x86_sse_loadu_ps:
9878 case Intrinsic::x86_sse2_loadu_pd:
9879 case Intrinsic::x86_sse2_loadu_dq:
9880 // Turn PPC lvx -> load if the pointer is known aligned.
9881 // Turn X86 loadups -> load if the pointer is known aligned.
9882 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9883 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009884 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009885 CI);
9886 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009887 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009888 break;
9889 case Intrinsic::ppc_altivec_stvx:
9890 case Intrinsic::ppc_altivec_stvxl:
9891 // Turn stvx -> store if the pointer is known aligned.
9892 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9893 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009894 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009895 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9896 return new StoreInst(II->getOperand(1), Ptr);
9897 }
9898 break;
9899 case Intrinsic::x86_sse_storeu_ps:
9900 case Intrinsic::x86_sse2_storeu_pd:
9901 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009902 // Turn X86 storeu -> store if the pointer is known aligned.
9903 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9904 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009905 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009906 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9907 return new StoreInst(II->getOperand(2), Ptr);
9908 }
9909 break;
9910
9911 case Intrinsic::x86_sse_cvttss2si: {
9912 // These intrinsics only demands the 0th element of its input vector. If
9913 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009914 unsigned VWidth =
9915 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9916 APInt DemandedElts(VWidth, 1);
9917 APInt UndefElts(VWidth, 0);
9918 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 UndefElts)) {
9920 II->setOperand(1, V);
9921 return II;
9922 }
9923 break;
9924 }
9925
9926 case Intrinsic::ppc_altivec_vperm:
9927 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9928 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9929 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009930
Chris Lattner0521e3c2008-06-18 04:33:20 +00009931 // Check that all of the elements are integer constants or undefs.
9932 bool AllEltsOk = true;
9933 for (unsigned i = 0; i != 16; ++i) {
9934 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9935 !isa<UndefValue>(Mask->getOperand(i))) {
9936 AllEltsOk = false;
9937 break;
9938 }
9939 }
9940
9941 if (AllEltsOk) {
9942 // Cast the input vectors to byte vectors.
9943 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9944 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009945 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009946
Chris Lattner0521e3c2008-06-18 04:33:20 +00009947 // Only extract each element once.
9948 Value *ExtractedElts[32];
9949 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9950
Chris Lattnere2ed0572006-04-06 19:19:17 +00009951 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009952 if (isa<UndefValue>(Mask->getOperand(i)))
9953 continue;
9954 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9955 Idx &= 31; // Match the hardware behavior.
9956
9957 if (ExtractedElts[Idx] == 0) {
9958 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009959 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneed707b2009-07-24 23:12:02 +00009960 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009961 InsertNewInstBefore(Elt, CI);
9962 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009963 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009964
Chris Lattner0521e3c2008-06-18 04:33:20 +00009965 // Insert this value into the result vector.
9966 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneed707b2009-07-24 23:12:02 +00009967 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009968 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009969 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009970 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009971 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009972 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009973 }
9974 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009975
Chris Lattner0521e3c2008-06-18 04:33:20 +00009976 case Intrinsic::stackrestore: {
9977 // If the save is right next to the restore, remove the restore. This can
9978 // happen when variable allocas are DCE'd.
9979 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9980 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9981 BasicBlock::iterator BI = SS;
9982 if (&*++BI == II)
9983 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009984 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009985 }
9986
9987 // Scan down this block to see if there is another stack restore in the
9988 // same block without an intervening call/alloca.
9989 BasicBlock::iterator BI = II;
9990 TerminatorInst *TI = II->getParent()->getTerminator();
9991 bool CannotRemove = false;
9992 for (++BI; &*BI != TI; ++BI) {
9993 if (isa<AllocaInst>(BI)) {
9994 CannotRemove = true;
9995 break;
9996 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009997 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9998 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9999 // If there is a stackrestore below this one, remove this one.
10000 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10001 return EraseInstFromFunction(CI);
10002 // Otherwise, ignore the intrinsic.
10003 } else {
10004 // If we found a non-intrinsic call, we can't remove the stack
10005 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010006 CannotRemove = true;
10007 break;
10008 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010009 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010010 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010011
10012 // If the stack restore is in a return/unwind block and if there are no
10013 // allocas or calls between the restore and the return, nuke the restore.
10014 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10015 return EraseInstFromFunction(CI);
10016 break;
10017 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010018 }
10019
Chris Lattner8b0ea312006-01-13 20:11:04 +000010020 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010021}
10022
10023// InvokeInst simplification
10024//
10025Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010026 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010027}
10028
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010029/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10030/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010031static bool isSafeToEliminateVarargsCast(const CallSite CS,
10032 const CastInst * const CI,
10033 const TargetData * const TD,
10034 const int ix) {
10035 if (!CI->isLosslessCast())
10036 return false;
10037
10038 // The size of ByVal arguments is derived from the type, so we
10039 // can't change to a type with a different size. If the size were
10040 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010041 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010042 return true;
10043
10044 const Type* SrcTy =
10045 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10046 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10047 if (!SrcTy->isSized() || !DstTy->isSized())
10048 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010049 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010050 return false;
10051 return true;
10052}
10053
Chris Lattnera44d8a22003-10-07 22:32:43 +000010054// visitCallSite - Improvements for call and invoke instructions.
10055//
10056Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010057 bool Changed = false;
10058
10059 // If the callee is a constexpr cast of a function, attempt to move the cast
10060 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010061 if (transformConstExprCastCall(CS)) return 0;
10062
Chris Lattner6c266db2003-10-07 22:54:13 +000010063 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010064
Chris Lattner08b22ec2005-05-13 07:09:09 +000010065 if (Function *CalleeF = dyn_cast<Function>(Callee))
10066 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10067 Instruction *OldCall = CS.getInstruction();
10068 // If the call and callee calling conventions don't match, this call must
10069 // be unreachable, as the call is undefined.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010070 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010071 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10072 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010073 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010074 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010075 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10076 return EraseInstFromFunction(*OldCall);
10077 return 0;
10078 }
10079
Chris Lattner17be6352004-10-18 02:59:09 +000010080 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10081 // This instruction is not reachable, just remove it. We insert a store to
10082 // undef so that we know that this code is not reachable, despite the fact
10083 // that we can't modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010084 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010085 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010086 CS.getInstruction());
10087
10088 if (!CS.getInstruction()->use_empty())
10089 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010090 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010091
10092 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10093 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010094 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb3056fa2009-07-21 18:03:38 +000010095 Context->getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010096 }
Chris Lattner17be6352004-10-18 02:59:09 +000010097 return EraseInstFromFunction(*CS.getInstruction());
10098 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010099
Duncan Sandscdb6d922007-09-17 10:26:40 +000010100 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10101 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10102 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10103 return transformCallThroughTrampoline(CS);
10104
Chris Lattner6c266db2003-10-07 22:54:13 +000010105 const PointerType *PTy = cast<PointerType>(Callee->getType());
10106 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10107 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010108 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010109 // See if we can optimize any arguments passed through the varargs area of
10110 // the call.
10111 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010112 E = CS.arg_end(); I != E; ++I, ++ix) {
10113 CastInst *CI = dyn_cast<CastInst>(*I);
10114 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10115 *I = CI->getOperand(0);
10116 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010117 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010118 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010119 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010120
Duncan Sandsf0c33542007-12-19 21:13:37 +000010121 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010122 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010123 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010124 Changed = true;
10125 }
10126
Chris Lattner6c266db2003-10-07 22:54:13 +000010127 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010128}
10129
Chris Lattner9fe38862003-06-19 17:00:31 +000010130// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10131// attempt to move the cast to the arguments of the call/invoke.
10132//
10133bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10134 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10135 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010136 if (CE->getOpcode() != Instruction::BitCast ||
10137 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010138 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010139 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010140 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010141 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010142
10143 // Okay, this is a cast from a function to a different type. Unless doing so
10144 // would cause a type conversion of one of our arguments, change this call to
10145 // be a direct call with arguments casted to the appropriate types.
10146 //
10147 const FunctionType *FT = Callee->getFunctionType();
10148 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010149 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010150
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010151 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010152 return false; // TODO: Handle multiple return values.
10153
Chris Lattnerf78616b2004-01-14 06:06:08 +000010154 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010155 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010156 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010157 // Conversion is ok if changing from one pointer type to another or from
10158 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010159 !((isa<PointerType>(OldRetTy) || !TD ||
10160 OldRetTy == TD->getIntPtrType()) &&
10161 (isa<PointerType>(NewRetTy) || !TD ||
10162 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010163 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010164
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010165 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010166 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010167 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010168 return false; // Cannot transform this return value.
10169
Chris Lattner58d74912008-03-12 17:45:29 +000010170 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010171 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010172 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010173 return false; // Attribute not compatible with transformed value.
10174 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010175
Chris Lattnerf78616b2004-01-14 06:06:08 +000010176 // If the callsite is an invoke instruction, and the return value is used by
10177 // a PHI node in a successor, we cannot change the return type of the call
10178 // because there is no place to put the cast instruction (without breaking
10179 // the critical edge). Bail out in this case.
10180 if (!Caller->use_empty())
10181 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10182 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10183 UI != E; ++UI)
10184 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10185 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010186 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010187 return false;
10188 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010189
10190 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10191 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010192
Chris Lattner9fe38862003-06-19 17:00:31 +000010193 CallSite::arg_iterator AI = CS.arg_begin();
10194 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10195 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010196 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010197
10198 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010199 return false; // Cannot transform this parameter value.
10200
Devang Patel19c87462008-09-26 22:53:05 +000010201 if (CallerPAL.getParamAttributes(i + 1)
10202 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010203 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010204
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010205 // Converting from one pointer type to another or between a pointer and an
10206 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010207 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010208 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10209 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010210 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010211 }
10212
10213 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010214 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010215 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010216
Chris Lattner58d74912008-03-12 17:45:29 +000010217 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10218 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010219 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010220 // won't be dropping them. Check that these extra arguments have attributes
10221 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010222 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10223 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010224 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010225 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010226 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010227 return false;
10228 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010229
Chris Lattner9fe38862003-06-19 17:00:31 +000010230 // Okay, we decided that this is a safe thing to do: go ahead and start
10231 // inserting cast instructions as necessary...
10232 std::vector<Value*> Args;
10233 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010234 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010235 attrVec.reserve(NumCommonArgs);
10236
10237 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010238 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010239
10240 // If the return value is not being used, the type may not be compatible
10241 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010242 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010243
10244 // Add the new return attributes.
10245 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010246 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010247
10248 AI = CS.arg_begin();
10249 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10250 const Type *ParamTy = FT->getParamType(i);
10251 if ((*AI)->getType() == ParamTy) {
10252 Args.push_back(*AI);
10253 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010254 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010255 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010256 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010257 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010258 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010259
10260 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010261 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010262 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010263 }
10264
10265 // If the function takes more arguments than the call was taking, add them
10266 // now...
10267 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010268 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010269
10270 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010271 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010272 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010273 errs() << "WARNING: While resolving call to function '"
10274 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010275 } else {
10276 // Add all of the arguments in their promoted form to the arg list...
10277 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10278 const Type *PTy = getPromotedType((*AI)->getType());
10279 if (PTy != (*AI)->getType()) {
10280 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010281 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10282 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010283 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 InsertNewInstBefore(Cast, *Caller);
10285 Args.push_back(Cast);
10286 } else {
10287 Args.push_back(*AI);
10288 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010289
Duncan Sandse1e520f2008-01-13 08:02:44 +000010290 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010291 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010292 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010293 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010294 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010295 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010296
Devang Patel19c87462008-09-26 22:53:05 +000010297 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10298 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10299
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010300 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010301 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010302
Eric Christophera66297a2009-07-25 02:45:27 +000010303 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10304 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010305
Chris Lattner9fe38862003-06-19 17:00:31 +000010306 Instruction *NC;
10307 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010308 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010309 Args.begin(), Args.end(),
10310 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010311 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010312 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010313 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010314 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10315 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010316 CallInst *CI = cast<CallInst>(Caller);
10317 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010318 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010319 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010320 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 }
10322
Chris Lattner6934a042007-02-11 01:23:03 +000010323 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010324 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010325 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010326 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010327 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010328 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010329 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010330
10331 // If this is an invoke instruction, we should insert it after the first
10332 // non-phi, instruction in the normal successor block.
10333 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010334 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010335 InsertNewInstBefore(NC, *I);
10336 } else {
10337 // Otherwise, it's a call, just insert cast right after the call instr
10338 InsertNewInstBefore(NC, *Caller);
10339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010340 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010341 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010342 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010343 }
10344 }
10345
10346 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10347 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010348 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010349 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010350 return true;
10351}
10352
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353// transformCallThroughTrampoline - Turn a call to a function created by the
10354// init_trampoline intrinsic into a direct call to the underlying function.
10355//
10356Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10357 Value *Callee = CS.getCalledValue();
10358 const PointerType *PTy = cast<PointerType>(Callee->getType());
10359 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010360 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010361
10362 // If the call already has the 'nest' attribute somewhere then give up -
10363 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010364 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010365 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366
10367 IntrinsicInst *Tramp =
10368 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10369
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010370 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010371 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10372 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10373
Devang Patel05988662008-09-25 21:00:45 +000010374 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010375 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 unsigned NestIdx = 1;
10377 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010378 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010379
10380 // Look for a parameter marked with the 'nest' attribute.
10381 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10382 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010383 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010384 // Record the parameter type and any other attributes.
10385 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010386 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 break;
10388 }
10389
10390 if (NestTy) {
10391 Instruction *Caller = CS.getInstruction();
10392 std::vector<Value*> NewArgs;
10393 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10394
Devang Patel05988662008-09-25 21:00:45 +000010395 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010396 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397
Duncan Sandscdb6d922007-09-17 10:26:40 +000010398 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010399 // mean appending it. Likewise for attributes.
10400
Devang Patel19c87462008-09-26 22:53:05 +000010401 // Add any result attributes.
10402 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010403 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010404
Duncan Sandscdb6d922007-09-17 10:26:40 +000010405 {
10406 unsigned Idx = 1;
10407 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10408 do {
10409 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010410 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010411 Value *NestVal = Tramp->getOperand(3);
10412 if (NestVal->getType() != NestTy)
10413 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10414 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010415 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010416 }
10417
10418 if (I == E)
10419 break;
10420
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010421 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010422 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010423 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010424 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010425 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010426
10427 ++Idx, ++I;
10428 } while (1);
10429 }
10430
Devang Patel19c87462008-09-26 22:53:05 +000010431 // Add any function attributes.
10432 if (Attributes Attr = Attrs.getFnAttributes())
10433 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10434
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 // The trampoline may have been bitcast to a bogus type (FTy).
10436 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010437 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438
Duncan Sandscdb6d922007-09-17 10:26:40 +000010439 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 NewTypes.reserve(FTy->getNumParams()+1);
10441
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010443 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 {
10445 unsigned Idx = 1;
10446 FunctionType::param_iterator I = FTy->param_begin(),
10447 E = FTy->param_end();
10448
10449 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010450 if (Idx == NestIdx)
10451 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453
10454 if (I == E)
10455 break;
10456
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010457 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010458 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459
10460 ++Idx, ++I;
10461 } while (1);
10462 }
10463
10464 // Replace the trampoline call with a direct call. Let the generic
10465 // code sort out any function type mismatches.
10466 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010467 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10468 FTy->isVarArg());
10469 Constant *NewCallee =
10470 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10471 NestF : Context->getConstantExprBitCast(NestF,
10472 Context->getPointerTypeUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010473 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10474 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010475
10476 Instruction *NewCaller;
10477 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010478 NewCaller = InvokeInst::Create(NewCallee,
10479 II->getNormalDest(), II->getUnwindDest(),
10480 NewArgs.begin(), NewArgs.end(),
10481 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010483 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010484 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010485 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10486 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010487 if (cast<CallInst>(Caller)->isTailCall())
10488 cast<CallInst>(NewCaller)->setTailCall();
10489 cast<CallInst>(NewCaller)->
10490 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010491 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010492 }
10493 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10494 Caller->replaceAllUsesWith(NewCaller);
10495 Caller->eraseFromParent();
10496 RemoveFromWorkList(Caller);
10497 return 0;
10498 }
10499 }
10500
10501 // Replace the trampoline call with a direct call. Since there is no 'nest'
10502 // parameter, there is no need to adjust the argument list. Let the generic
10503 // code sort out any function type mismatches.
10504 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010505 NestF->getType() == PTy ? NestF :
10506 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010507 CS.setCalledFunction(NewCallee);
10508 return CS.getInstruction();
10509}
10510
Chris Lattner7da52b22006-11-01 04:51:18 +000010511/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10512/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10513/// and a single binop.
10514Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10515 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010516 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010517 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010518 Value *LHSVal = FirstInst->getOperand(0);
10519 Value *RHSVal = FirstInst->getOperand(1);
10520
10521 const Type *LHSType = LHSVal->getType();
10522 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010523
10524 // Scan to see if all operands are the same opcode, all have one use, and all
10525 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010526 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010527 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010528 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010529 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010530 // types or GEP's with different index types.
10531 I->getOperand(0)->getType() != LHSType ||
10532 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010533 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010534
10535 // If they are CmpInst instructions, check their predicates
10536 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10537 if (cast<CmpInst>(I)->getPredicate() !=
10538 cast<CmpInst>(FirstInst)->getPredicate())
10539 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010540
10541 // Keep track of which operand needs a phi node.
10542 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10543 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010544 }
10545
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010546 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010547
Chris Lattner7da52b22006-11-01 04:51:18 +000010548 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010549 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010550 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010551 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010552 NewLHS = PHINode::Create(LHSType,
10553 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010554 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10555 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010556 InsertNewInstBefore(NewLHS, PN);
10557 LHSVal = NewLHS;
10558 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010559
10560 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010561 NewRHS = PHINode::Create(RHSType,
10562 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010563 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10564 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010565 InsertNewInstBefore(NewRHS, PN);
10566 RHSVal = NewRHS;
10567 }
10568
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010569 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010570 if (NewLHS || NewRHS) {
10571 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10572 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10573 if (NewLHS) {
10574 Value *NewInLHS = InInst->getOperand(0);
10575 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10576 }
10577 if (NewRHS) {
10578 Value *NewInRHS = InInst->getOperand(1);
10579 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10580 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010581 }
10582 }
10583
Chris Lattner7da52b22006-11-01 04:51:18 +000010584 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010585 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010586 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010587 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10588 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010589}
10590
Chris Lattner05f18922008-12-01 02:34:36 +000010591Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10592 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10593
10594 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10595 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010596 // This is true if all GEP bases are allocas and if all indices into them are
10597 // constants.
10598 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010599
10600 // Scan to see if all operands are the same opcode, all have one use, and all
10601 // kill their operands (i.e. the operands have one use).
10602 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10603 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10604 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10605 GEP->getNumOperands() != FirstInst->getNumOperands())
10606 return 0;
10607
Chris Lattner36d3e322009-02-21 00:46:50 +000010608 // Keep track of whether or not all GEPs are of alloca pointers.
10609 if (AllBasePointersAreAllocas &&
10610 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10611 !GEP->hasAllConstantIndices()))
10612 AllBasePointersAreAllocas = false;
10613
Chris Lattner05f18922008-12-01 02:34:36 +000010614 // Compare the operand lists.
10615 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10616 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10617 continue;
10618
10619 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10620 // if one of the PHIs has a constant for the index. The index may be
10621 // substantially cheaper to compute for the constants, so making it a
10622 // variable index could pessimize the path. This also handles the case
10623 // for struct indices, which must always be constant.
10624 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10625 isa<ConstantInt>(GEP->getOperand(op)))
10626 return 0;
10627
10628 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10629 return 0;
10630 FixedOperands[op] = 0; // Needs a PHI.
10631 }
10632 }
10633
Chris Lattner36d3e322009-02-21 00:46:50 +000010634 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010635 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010636 // offset calculation, but all the predecessors will have to materialize the
10637 // stack address into a register anyway. We'd actually rather *clone* the
10638 // load up into the predecessors so that we have a load of a gep of an alloca,
10639 // which can usually all be folded into the load.
10640 if (AllBasePointersAreAllocas)
10641 return 0;
10642
Chris Lattner05f18922008-12-01 02:34:36 +000010643 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10644 // that is variable.
10645 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10646
10647 bool HasAnyPHIs = false;
10648 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10649 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10650 Value *FirstOp = FirstInst->getOperand(i);
10651 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10652 FirstOp->getName()+".pn");
10653 InsertNewInstBefore(NewPN, PN);
10654
10655 NewPN->reserveOperandSpace(e);
10656 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10657 OperandPhis[i] = NewPN;
10658 FixedOperands[i] = NewPN;
10659 HasAnyPHIs = true;
10660 }
10661
10662
10663 // Add all operands to the new PHIs.
10664 if (HasAnyPHIs) {
10665 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10666 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10667 BasicBlock *InBB = PN.getIncomingBlock(i);
10668
10669 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10670 if (PHINode *OpPhi = OperandPhis[op])
10671 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10672 }
10673 }
10674
10675 Value *Base = FixedOperands[0];
10676 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10677 FixedOperands.end());
10678}
10679
10680
Chris Lattner21550882009-02-23 05:56:17 +000010681/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10682/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010683/// obvious the value of the load is not changed from the point of the load to
10684/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010685///
10686/// Finally, it is safe, but not profitable, to sink a load targetting a
10687/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10688/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010689static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010690 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10691
10692 for (++BBI; BBI != E; ++BBI)
10693 if (BBI->mayWriteToMemory())
10694 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010695
10696 // Check for non-address taken alloca. If not address-taken already, it isn't
10697 // profitable to do this xform.
10698 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10699 bool isAddressTaken = false;
10700 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10701 UI != E; ++UI) {
10702 if (isa<LoadInst>(UI)) continue;
10703 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10704 // If storing TO the alloca, then the address isn't taken.
10705 if (SI->getOperand(1) == AI) continue;
10706 }
10707 isAddressTaken = true;
10708 break;
10709 }
10710
Chris Lattner36d3e322009-02-21 00:46:50 +000010711 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010712 return false;
10713 }
10714
Chris Lattner36d3e322009-02-21 00:46:50 +000010715 // If this load is a load from a GEP with a constant offset from an alloca,
10716 // then we don't want to sink it. In its present form, it will be
10717 // load [constant stack offset]. Sinking it will cause us to have to
10718 // materialize the stack addresses in each predecessor in a register only to
10719 // do a shared load from register in the successor.
10720 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10721 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10722 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10723 return false;
10724
Chris Lattner76c73142006-11-01 07:13:54 +000010725 return true;
10726}
10727
Chris Lattner9fe38862003-06-19 17:00:31 +000010728
Chris Lattnerbac32862004-11-14 19:13:23 +000010729// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10730// operator and they all are only used by the PHI, PHI together their
10731// inputs, and do the operation once, to the result of the PHI.
10732Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10733 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10734
10735 // Scan the instruction, looking for input operations that can be folded away.
10736 // If all input operands to the phi are the same instruction (e.g. a cast from
10737 // the same type or "+42") we can pull the operation through the PHI, reducing
10738 // code size and simplifying code.
10739 Constant *ConstantOp = 0;
10740 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010741 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010742 if (isa<CastInst>(FirstInst)) {
10743 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010744 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010745 // Can fold binop, compare or shift here if the RHS is a constant,
10746 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010747 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010748 if (ConstantOp == 0)
10749 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010750 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10751 isVolatile = LI->isVolatile();
10752 // We can't sink the load if the loaded value could be modified between the
10753 // load and the PHI.
10754 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010755 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010756 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010757
10758 // If the PHI is of volatile loads and the load block has multiple
10759 // successors, sinking it would remove a load of the volatile value from
10760 // the path through the other successor.
10761 if (isVolatile &&
10762 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10763 return 0;
10764
Chris Lattner9c080502006-11-01 07:43:41 +000010765 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010766 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010767 } else {
10768 return 0; // Cannot fold this operation.
10769 }
10770
10771 // Check to see if all arguments are the same operation.
10772 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10773 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10774 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010775 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010776 return 0;
10777 if (CastSrcTy) {
10778 if (I->getOperand(0)->getType() != CastSrcTy)
10779 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010780 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010781 // We can't sink the load if the loaded value could be modified between
10782 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010783 if (LI->isVolatile() != isVolatile ||
10784 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010785 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010786 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010787
Chris Lattner71042962008-07-08 17:18:32 +000010788 // If the PHI is of volatile loads and the load block has multiple
10789 // successors, sinking it would remove a load of the volatile value from
10790 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010791 if (isVolatile &&
10792 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10793 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010794
Chris Lattnerbac32862004-11-14 19:13:23 +000010795 } else if (I->getOperand(1) != ConstantOp) {
10796 return 0;
10797 }
10798 }
10799
10800 // Okay, they are all the same operation. Create a new PHI node of the
10801 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010802 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10803 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010804 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010805
10806 Value *InVal = FirstInst->getOperand(0);
10807 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010808
10809 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010810 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10811 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10812 if (NewInVal != InVal)
10813 InVal = 0;
10814 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10815 }
10816
10817 Value *PhiVal;
10818 if (InVal) {
10819 // The new PHI unions all of the same values together. This is really
10820 // common, so we handle it intelligently here for compile-time speed.
10821 PhiVal = InVal;
10822 delete NewPN;
10823 } else {
10824 InsertNewInstBefore(NewPN, PN);
10825 PhiVal = NewPN;
10826 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010827
Chris Lattnerbac32862004-11-14 19:13:23 +000010828 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010829 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010830 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010831 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010832 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010833 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010834 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010835 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010836 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10837
10838 // If this was a volatile load that we are merging, make sure to loop through
10839 // and mark all the input loads as non-volatile. If we don't do this, we will
10840 // insert a new volatile load and the old ones will not be deletable.
10841 if (isVolatile)
10842 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10843 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10844
10845 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010846}
Chris Lattnera1be5662002-05-02 17:06:02 +000010847
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010848/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10849/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010850static bool DeadPHICycle(PHINode *PN,
10851 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010852 if (PN->use_empty()) return true;
10853 if (!PN->hasOneUse()) return false;
10854
10855 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010856 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010857 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010858
10859 // Don't scan crazily complex things.
10860 if (PotentiallyDeadPHIs.size() == 16)
10861 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010862
10863 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10864 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010865
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010866 return false;
10867}
10868
Chris Lattnercf5008a2007-11-06 21:52:06 +000010869/// PHIsEqualValue - Return true if this phi node is always equal to
10870/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10871/// z = some value; x = phi (y, z); y = phi (x, z)
10872static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10873 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10874 // See if we already saw this PHI node.
10875 if (!ValueEqualPHIs.insert(PN))
10876 return true;
10877
10878 // Don't scan crazily complex things.
10879 if (ValueEqualPHIs.size() == 16)
10880 return false;
10881
10882 // Scan the operands to see if they are either phi nodes or are equal to
10883 // the value.
10884 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10885 Value *Op = PN->getIncomingValue(i);
10886 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10887 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10888 return false;
10889 } else if (Op != NonPhiInVal)
10890 return false;
10891 }
10892
10893 return true;
10894}
10895
10896
Chris Lattner473945d2002-05-06 18:06:38 +000010897// PHINode simplification
10898//
Chris Lattner7e708292002-06-25 16:13:24 +000010899Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010900 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010901 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010902
Owen Anderson7e057142006-07-10 22:03:18 +000010903 if (Value *V = PN.hasConstantValue())
10904 return ReplaceInstUsesWith(PN, V);
10905
Owen Anderson7e057142006-07-10 22:03:18 +000010906 // If all PHI operands are the same operation, pull them through the PHI,
10907 // reducing code size.
10908 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010909 isa<Instruction>(PN.getIncomingValue(1)) &&
10910 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10911 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10912 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10913 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010914 PN.getIncomingValue(0)->hasOneUse())
10915 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10916 return Result;
10917
10918 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10919 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10920 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010921 if (PN.hasOneUse()) {
10922 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10923 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010924 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010925 PotentiallyDeadPHIs.insert(&PN);
10926 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010927 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010928 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010929
10930 // If this phi has a single use, and if that use just computes a value for
10931 // the next iteration of a loop, delete the phi. This occurs with unused
10932 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10933 // common case here is good because the only other things that catch this
10934 // are induction variable analysis (sometimes) and ADCE, which is only run
10935 // late.
10936 if (PHIUser->hasOneUse() &&
10937 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10938 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010939 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010940 }
10941 }
Owen Anderson7e057142006-07-10 22:03:18 +000010942
Chris Lattnercf5008a2007-11-06 21:52:06 +000010943 // We sometimes end up with phi cycles that non-obviously end up being the
10944 // same value, for example:
10945 // z = some value; x = phi (y, z); y = phi (x, z)
10946 // where the phi nodes don't necessarily need to be in the same block. Do a
10947 // quick check to see if the PHI node only contains a single non-phi value, if
10948 // so, scan to see if the phi cycle is actually equal to that value.
10949 {
10950 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10951 // Scan for the first non-phi operand.
10952 while (InValNo != NumOperandVals &&
10953 isa<PHINode>(PN.getIncomingValue(InValNo)))
10954 ++InValNo;
10955
10956 if (InValNo != NumOperandVals) {
10957 Value *NonPhiInVal = PN.getOperand(InValNo);
10958
10959 // Scan the rest of the operands to see if there are any conflicts, if so
10960 // there is no need to recursively scan other phis.
10961 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10962 Value *OpVal = PN.getIncomingValue(InValNo);
10963 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10964 break;
10965 }
10966
10967 // If we scanned over all operands, then we have one unique value plus
10968 // phi values. Scan PHI nodes to see if they all merge in each other or
10969 // the value.
10970 if (InValNo == NumOperandVals) {
10971 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10972 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10973 return ReplaceInstUsesWith(PN, NonPhiInVal);
10974 }
10975 }
10976 }
Chris Lattner60921c92003-12-19 05:58:40 +000010977 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010978}
10979
Reid Spencer17212df2006-12-12 09:18:51 +000010980static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10981 Instruction *InsertPoint,
10982 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010983 unsigned PtrSize = DTy->getScalarSizeInBits();
10984 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010985 // We must cast correctly to the pointer type. Ensure that we
10986 // sign extend the integer value if it is smaller as this is
10987 // used for address computation.
10988 Instruction::CastOps opcode =
10989 (VTySize < PtrSize ? Instruction::SExt :
10990 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10991 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010992}
10993
Chris Lattnera1be5662002-05-02 17:06:02 +000010994
Chris Lattner7e708292002-06-25 16:13:24 +000010995Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010996 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010997 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010998 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010999 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011001
Chris Lattnere87597f2004-10-16 18:11:37 +000011002 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011003 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011004
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011005 bool HasZeroPointerIndex = false;
11006 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11007 HasZeroPointerIndex = C->isNullValue();
11008
11009 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011010 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011011
Chris Lattner28977af2004-04-05 01:30:19 +000011012 // Eliminate unneeded casts for indices.
11013 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011014
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011015 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011016 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11017 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011018 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011019 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011020 if (CI->getOpcode() == Instruction::ZExt ||
11021 CI->getOpcode() == Instruction::SExt) {
11022 const Type *SrcTy = CI->getOperand(0)->getType();
11023 // We can eliminate a cast from i32 to i64 iff the target
11024 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011025 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011026 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011027 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011028 }
11029 }
11030 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011031 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011032 // to what we need. If narrower, sign-extend it to what we need.
11033 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011034 // insert it. This explicit cast can make subsequent optimizations more
11035 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011036 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011037 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011038 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011039 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011040 MadeChange = true;
11041 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011042 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11043 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011044 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011045 MadeChange = true;
11046 }
Eric Christophera66297a2009-07-25 02:45:27 +000011047 } else if (TD->getTypeSizeInBits(Op->getType())
11048 < TD->getPointerSizeInBits()) {
Dan Gohman4f833d42008-09-11 23:06:38 +000011049 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011050 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011051 MadeChange = true;
11052 } else {
11053 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11054 GEP);
11055 *i = Op;
11056 MadeChange = true;
11057 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011058 }
Chris Lattner28977af2004-04-05 01:30:19 +000011059 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011060 }
Chris Lattner28977af2004-04-05 01:30:19 +000011061 if (MadeChange) return &GEP;
11062
Chris Lattner90ac28c2002-08-02 19:29:35 +000011063 // Combine Indices - If the source pointer to this getelementptr instruction
11064 // is a getelementptr instruction, combine the indices of the two
11065 // getelementptr instructions into a single instruction.
11066 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011067 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011068 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011069 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011070
11071 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011072 // Note that if our source is a gep chain itself that we wait for that
11073 // chain to be resolved before we perform this transformation. This
11074 // avoids us creating a TON of code in some cases.
11075 //
11076 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11077 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11078 return 0; // Wait until our source is folded to completion.
11079
Chris Lattner72588fc2007-02-15 22:48:32 +000011080 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011081
11082 // Find out whether the last index in the source GEP is a sequential idx.
11083 bool EndsWithSequential = false;
11084 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11085 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011086 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011087
Chris Lattner90ac28c2002-08-02 19:29:35 +000011088 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011089 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011090 // Replace: gep (gep %P, long B), long A, ...
11091 // With: T = long A+B; gep %P, T, ...
11092 //
Chris Lattner620ce142004-05-07 22:09:22 +000011093 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011094 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011095 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011096 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011097 Sum = SO1;
11098 } else {
11099 // If they aren't the same type, convert both to an integer of the
11100 // target's pointer size.
11101 if (SO1->getType() != GO1->getType()) {
11102 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011103 SO1 =
11104 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011105 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011106 GO1 =
11107 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011108 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011109 unsigned PS = TD->getPointerSizeInBits();
11110 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011111 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011112 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011113
Duncan Sands514ab342007-11-01 20:53:16 +000011114 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011115 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011116 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011117 } else {
11118 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011119 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11120 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011121 }
11122 }
11123 }
Chris Lattner620ce142004-05-07 22:09:22 +000011124 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011125 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11126 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011127 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011128 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011129 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011130 }
Chris Lattner28977af2004-04-05 01:30:19 +000011131 }
Chris Lattner620ce142004-05-07 22:09:22 +000011132
11133 // Recycle the GEP we already have if possible.
11134 if (SrcGEPOperands.size() == 2) {
11135 GEP.setOperand(0, SrcGEPOperands[0]);
11136 GEP.setOperand(1, Sum);
11137 return &GEP;
11138 } else {
11139 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11140 SrcGEPOperands.end()-1);
11141 Indices.push_back(Sum);
11142 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11143 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011144 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011145 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011146 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011147 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011148 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11149 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011150 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11151 }
11152
11153 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011154 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11155 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011156
Chris Lattner620ce142004-05-07 22:09:22 +000011157 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011158 // GEP of global variable. If all of the indices for this GEP are
11159 // constants, we can promote this to a constexpr instead of an instruction.
11160
11161 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011162 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011163 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11164 for (; I != E && isa<Constant>(*I); ++I)
11165 Indices.push_back(cast<Constant>(*I));
11166
11167 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011168 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011169 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011170
11171 // Replace all uses of the GEP with the new constexpr...
11172 return ReplaceInstUsesWith(GEP, CE);
11173 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011174 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011175 if (!isa<PointerType>(X->getType())) {
11176 // Not interesting. Source pointer must be a cast from pointer.
11177 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011178 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11179 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011180 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011181 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11182 // into : GEP i8* X, ...
11183 //
Chris Lattnereed48272005-09-13 00:40:14 +000011184 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011185 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11186 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011187 if (const ArrayType *CATy =
11188 dyn_cast<ArrayType>(CPTy->getElementType())) {
11189 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11190 if (CATy->getElementType() == XTy->getElementType()) {
11191 // -> GEP i8* X, ...
11192 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11193 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11194 GEP.getName());
11195 } else if (const ArrayType *XATy =
11196 dyn_cast<ArrayType>(XTy->getElementType())) {
11197 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011198 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011199 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011200 // At this point, we know that the cast source type is a pointer
11201 // to an array of the same type as the destination pointer
11202 // array. Because the array type is never stepped over (there
11203 // is a leading zero) we can fold the cast into this GEP.
11204 GEP.setOperand(0, X);
11205 return &GEP;
11206 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011207 }
11208 }
Chris Lattnereed48272005-09-13 00:40:14 +000011209 } else if (GEP.getNumOperands() == 2) {
11210 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011211 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11212 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011213 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11214 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011215 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011216 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11217 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011218 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011219 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011220 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011221 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011222 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011223 // V and GEP are both pointer types --> BitCast
11224 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011225 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011226
11227 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011228 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011229 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011230 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011231
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011232 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011233 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011234 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011235
11236 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11237 // allow either a mul, shift, or constant here.
11238 Value *NewIdx = 0;
11239 ConstantInt *Scale = 0;
11240 if (ArrayEltSize == 1) {
11241 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011242 Scale =
Owen Andersoneed707b2009-07-24 23:12:02 +000011243 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011244 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011245 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011246 Scale = CI;
11247 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11248 if (Inst->getOpcode() == Instruction::Shl &&
11249 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011250 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11251 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011252 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011253 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011254 NewIdx = Inst->getOperand(0);
11255 } else if (Inst->getOpcode() == Instruction::Mul &&
11256 isa<ConstantInt>(Inst->getOperand(1))) {
11257 Scale = cast<ConstantInt>(Inst->getOperand(1));
11258 NewIdx = Inst->getOperand(0);
11259 }
11260 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011261
Chris Lattner7835cdd2005-09-13 18:36:04 +000011262 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011263 // out, perform the transformation. Note, we don't know whether Scale is
11264 // signed or not. We'll use unsigned version of division/modulo
11265 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011266 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011267 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011268 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011269 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011270 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011271 Constant *C =
11272 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011273 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011274 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011275 NewIdx = InsertNewInstBefore(Sc, GEP);
11276 }
11277
11278 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011279 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011280 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011281 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011282 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011283 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011284 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11285 // The NewGEP must be pointer typed, so must the old one -> BitCast
11286 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011287 }
11288 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011289 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011290 }
Chris Lattner58407792009-01-09 04:53:57 +000011291
Chris Lattner46cd5a12009-01-09 05:44:56 +000011292 /// See if we can simplify:
11293 /// X = bitcast A to B*
11294 /// Y = gep X, <...constant indices...>
11295 /// into a gep of the original struct. This is important for SROA and alias
11296 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011297 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011298 if (TD &&
11299 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011300 // Determine how much the GEP moves the pointer. We are guaranteed to get
11301 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011302 ConstantInt *OffsetV =
11303 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011304 int64_t Offset = OffsetV->getSExtValue();
11305
11306 // If this GEP instruction doesn't move the pointer, just replace the GEP
11307 // with a bitcast of the real input to the dest type.
11308 if (Offset == 0) {
11309 // If the bitcast is of an allocation, and the allocation will be
11310 // converted to match the type of the cast, don't touch this.
11311 if (isa<AllocationInst>(BCI->getOperand(0))) {
11312 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11313 if (Instruction *I = visitBitCast(*BCI)) {
11314 if (I != BCI) {
11315 I->takeName(BCI);
11316 BCI->getParent()->getInstList().insert(BCI, I);
11317 ReplaceInstUsesWith(*BCI, I);
11318 }
11319 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011320 }
Chris Lattner58407792009-01-09 04:53:57 +000011321 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011322 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011323 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011324
11325 // Otherwise, if the offset is non-zero, we need to find out if there is a
11326 // field at Offset in 'A's type. If so, we can pull the cast through the
11327 // GEP.
11328 SmallVector<Value*, 8> NewIndices;
11329 const Type *InTy =
11330 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011331 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011332 Instruction *NGEP =
11333 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11334 NewIndices.end());
11335 if (NGEP->getType() == GEP.getType()) return NGEP;
11336 InsertNewInstBefore(NGEP, GEP);
11337 NGEP->takeName(&GEP);
11338 return new BitCastInst(NGEP, GEP.getType());
11339 }
Chris Lattner58407792009-01-09 04:53:57 +000011340 }
11341 }
11342
Chris Lattner8a2a3112001-12-14 16:52:21 +000011343 return 0;
11344}
11345
Chris Lattner0864acf2002-11-04 16:18:53 +000011346Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11347 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011348 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011349 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11350 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011351 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011352 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011353
11354 // Create and insert the replacement instruction...
11355 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011356 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011357 else {
11358 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011359 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011360 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011361
11362 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011363
Chris Lattner0864acf2002-11-04 16:18:53 +000011364 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011365 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011366 //
11367 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011368 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011369
11370 // Now that I is pointing to the first non-allocation-inst in the block,
11371 // insert our getelementptr instruction...
11372 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011373 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011374 Value *Idx[2];
11375 Idx[0] = NullIdx;
11376 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011377 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11378 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011379
11380 // Now make everything use the getelementptr instead of the original
11381 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011382 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011383 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011384 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011385 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011386 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011387
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011388 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011389 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011390 // Note that we only do this for alloca's, because malloc should allocate
11391 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011392 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011393 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011394
11395 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11396 if (AI.getAlignment() == 0)
11397 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11398 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011399
Chris Lattner0864acf2002-11-04 16:18:53 +000011400 return 0;
11401}
11402
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011403Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11404 Value *Op = FI.getOperand(0);
11405
Chris Lattner17be6352004-10-18 02:59:09 +000011406 // free undef -> unreachable.
11407 if (isa<UndefValue>(Op)) {
11408 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000011409 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000011410 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011411 return EraseInstFromFunction(FI);
11412 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011413
Chris Lattner6160e852004-02-28 04:57:37 +000011414 // If we have 'free null' delete the instruction. This can happen in stl code
11415 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011416 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011417 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011418
11419 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11420 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11421 FI.setOperand(0, CI->getOperand(0));
11422 return &FI;
11423 }
11424
11425 // Change free (gep X, 0,0,0,0) into free(X)
11426 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11427 if (GEPI->hasAllZeroIndices()) {
11428 AddToWorkList(GEPI);
11429 FI.setOperand(0, GEPI->getOperand(0));
11430 return &FI;
11431 }
11432 }
11433
11434 // Change free(malloc) into nothing, if the malloc has a single use.
11435 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11436 if (MI->hasOneUse()) {
11437 EraseInstFromFunction(FI);
11438 return EraseInstFromFunction(*MI);
11439 }
Chris Lattner6160e852004-02-28 04:57:37 +000011440
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011441 return 0;
11442}
11443
11444
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011445/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011446static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011447 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011448 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011449 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011450 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011451
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011452 if (TD) {
11453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11454 // Instead of loading constant c string, use corresponding integer value
11455 // directly if string length is small enough.
11456 std::string Str;
11457 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11458 unsigned len = Str.length();
11459 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11460 unsigned numBits = Ty->getPrimitiveSizeInBits();
11461 // Replace LI with immediate integer store.
11462 if ((numBits >> 3) == len + 1) {
11463 APInt StrVal(numBits, 0);
11464 APInt SingleChar(numBits, 0);
11465 if (TD->isLittleEndian()) {
11466 for (signed i = len-1; i >= 0; i--) {
11467 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11468 StrVal = (StrVal << 8) | SingleChar;
11469 }
11470 } else {
11471 for (unsigned i = 0; i < len; i++) {
11472 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11473 StrVal = (StrVal << 8) | SingleChar;
11474 }
11475 // Append NULL at the end.
11476 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011477 StrVal = (StrVal << 8) | SingleChar;
11478 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011479 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011480 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011481 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011482 }
11483 }
11484 }
11485
Mon P Wang6753f952009-02-07 22:19:29 +000011486 const PointerType *DestTy = cast<PointerType>(CI->getType());
11487 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011488 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011489
11490 // If the address spaces don't match, don't eliminate the cast.
11491 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11492 return 0;
11493
Chris Lattnerb89e0712004-07-13 01:49:43 +000011494 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011495
Reid Spencer42230162007-01-22 05:51:25 +000011496 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011497 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011498 // If the source is an array, the code below will not succeed. Check to
11499 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11500 // constants.
11501 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11502 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11503 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011504 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011505 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11506 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011507 SrcTy = cast<PointerType>(CastOp->getType());
11508 SrcPTy = SrcTy->getElementType();
11509 }
11510
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011511 if (IC.getTargetData() &&
11512 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011513 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011514 // Do not allow turning this into a load of an integer, which is then
11515 // casted to a pointer, this pessimizes pointer analysis a lot.
11516 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011517 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11518 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011519
Chris Lattnerf9527852005-01-31 04:50:46 +000011520 // Okay, we are casting from one integer or pointer type to another of
11521 // the same size. Instead of casting the pointer before the load, cast
11522 // the result of the loaded value.
11523 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11524 CI->getName(),
11525 LI.isVolatile()),LI);
11526 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011527 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011528 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011529 }
11530 }
11531 return 0;
11532}
11533
Chris Lattner833b8a42003-06-26 05:06:25 +000011534Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11535 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011536
Dan Gohman9941f742007-07-20 16:34:21 +000011537 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011538 if (TD) {
11539 unsigned KnownAlign =
11540 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11541 if (KnownAlign >
11542 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11543 LI.getAlignment()))
11544 LI.setAlignment(KnownAlign);
11545 }
Dan Gohman9941f742007-07-20 16:34:21 +000011546
Chris Lattner37366c12005-05-01 04:24:53 +000011547 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011548 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011549 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011550 return Res;
11551
11552 // None of the following transforms are legal for volatile loads.
11553 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011554
Dan Gohman2276a7b2008-10-15 23:19:35 +000011555 // Do really simple store-to-load forwarding and load CSE, to catch cases
11556 // where there are several consequtive memory accesses to the same location,
11557 // separated by a few arithmetic operations.
11558 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011559 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11560 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011561
Christopher Lambb15147e2007-12-29 07:56:53 +000011562 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11563 const Value *GEPI0 = GEPI->getOperand(0);
11564 // TODO: Consider a target hook for valid address spaces for this xform.
11565 if (isa<ConstantPointerNull>(GEPI0) &&
11566 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011567 // Insert a new store to null instruction before the load to indicate
11568 // that this code is not reachable. We do this instead of inserting
11569 // an unreachable instruction directly because we cannot modify the
11570 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011571 new StoreInst(Context->getUndef(LI.getType()),
11572 Context->getNullValue(Op->getType()), &LI);
11573 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011574 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011575 }
Chris Lattner37366c12005-05-01 04:24:53 +000011576
Chris Lattnere87597f2004-10-16 18:11:37 +000011577 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011578 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011579 // TODO: Consider a target hook for valid address spaces for this xform.
11580 if (isa<UndefValue>(C) || (C->isNullValue() &&
11581 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011582 // Insert a new store to null instruction before the load to indicate that
11583 // this code is not reachable. We do this instead of inserting an
11584 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011585 new StoreInst(Context->getUndef(LI.getType()),
11586 Context->getNullValue(Op->getType()), &LI);
11587 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011588 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011589
Chris Lattnere87597f2004-10-16 18:11:37 +000011590 // Instcombine load (constant global) into the value loaded.
11591 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011592 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011593 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011594
Chris Lattnere87597f2004-10-16 18:11:37 +000011595 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011596 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011597 if (CE->getOpcode() == Instruction::GetElementPtr) {
11598 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011599 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011600 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011601 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011602 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011603 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011604 if (CE->getOperand(0)->isNullValue()) {
11605 // Insert a new store to null instruction before the load to indicate
11606 // that this code is not reachable. We do this instead of inserting
11607 // an unreachable instruction directly because we cannot modify the
11608 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011609 new StoreInst(Context->getUndef(LI.getType()),
11610 Context->getNullValue(Op->getType()), &LI);
11611 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011612 }
11613
Reid Spencer3da59db2006-11-27 01:05:10 +000011614 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011615 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011616 return Res;
11617 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011618 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011619 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011620
11621 // If this load comes from anywhere in a constant global, and if the global
11622 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011623 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011624 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011625 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011626 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011627 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011628 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011629 }
11630 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011631
Chris Lattner37366c12005-05-01 04:24:53 +000011632 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011633 // Change select and PHI nodes to select values instead of addresses: this
11634 // helps alias analysis out a lot, allows many others simplifications, and
11635 // exposes redundancy in the code.
11636 //
11637 // Note that we cannot do the transformation unless we know that the
11638 // introduced loads cannot trap! Something like this is valid as long as
11639 // the condition is always false: load (select bool %C, int* null, int* %G),
11640 // but it would not be valid if we transformed it to load from null
11641 // unconditionally.
11642 //
11643 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11644 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011645 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11646 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011647 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011648 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011649 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011650 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011651 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011652 }
11653
Chris Lattner684fe212004-09-23 15:46:00 +000011654 // load (select (cond, null, P)) -> load P
11655 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11656 if (C->isNullValue()) {
11657 LI.setOperand(0, SI->getOperand(2));
11658 return &LI;
11659 }
11660
11661 // load (select (cond, P, null)) -> load P
11662 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11663 if (C->isNullValue()) {
11664 LI.setOperand(0, SI->getOperand(1));
11665 return &LI;
11666 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011667 }
11668 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011669 return 0;
11670}
11671
Reid Spencer55af2b52007-01-19 21:20:31 +000011672/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011673/// when possible. This makes it generally easy to do alias analysis and/or
11674/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011675static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11676 User *CI = cast<User>(SI.getOperand(1));
11677 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011678 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011679
11680 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011681 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11682 if (SrcTy == 0) return 0;
11683
11684 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011685
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011686 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11687 return 0;
11688
Chris Lattner3914f722009-01-24 01:00:13 +000011689 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11690 /// to its first element. This allows us to handle things like:
11691 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11692 /// on 32-bit hosts.
11693 SmallVector<Value*, 4> NewGEPIndices;
11694
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011695 // If the source is an array, the code below will not succeed. Check to
11696 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11697 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011698 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11699 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011700 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011701 NewGEPIndices.push_back(Zero);
11702
11703 while (1) {
11704 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011705 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011706 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011707 NewGEPIndices.push_back(Zero);
11708 SrcPTy = STy->getElementType(0);
11709 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11710 NewGEPIndices.push_back(Zero);
11711 SrcPTy = ATy->getElementType();
11712 } else {
11713 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011714 }
Chris Lattner3914f722009-01-24 01:00:13 +000011715 }
11716
Owen Andersond672ecb2009-07-03 00:17:18 +000011717 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011718 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011719
11720 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11721 return 0;
11722
Chris Lattner71759c42009-01-16 20:12:52 +000011723 // If the pointers point into different address spaces or if they point to
11724 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011725 if (!IC.getTargetData() ||
11726 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011727 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011728 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11729 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011730 return 0;
11731
11732 // Okay, we are casting from one integer or pointer type to another of
11733 // the same size. Instead of casting the pointer before
11734 // the store, cast the value to be stored.
11735 Value *NewCast;
11736 Value *SIOp0 = SI.getOperand(0);
11737 Instruction::CastOps opcode = Instruction::BitCast;
11738 const Type* CastSrcTy = SIOp0->getType();
11739 const Type* CastDstTy = SrcPTy;
11740 if (isa<PointerType>(CastDstTy)) {
11741 if (CastSrcTy->isInteger())
11742 opcode = Instruction::IntToPtr;
11743 } else if (isa<IntegerType>(CastDstTy)) {
11744 if (isa<PointerType>(SIOp0->getType()))
11745 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011746 }
Chris Lattner3914f722009-01-24 01:00:13 +000011747
11748 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11749 // emit a GEP to index into its first field.
11750 if (!NewGEPIndices.empty()) {
11751 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011752 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011753 NewGEPIndices.size());
11754 else
11755 CastOp = IC.InsertNewInstBefore(
11756 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11757 NewGEPIndices.end()), SI);
11758 }
11759
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011760 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011761 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011762 else
11763 NewCast = IC.InsertNewInstBefore(
11764 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11765 SI);
11766 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011767}
11768
Chris Lattner4aebaee2008-11-27 08:56:30 +000011769/// equivalentAddressValues - Test if A and B will obviously have the same
11770/// value. This includes recognizing that %t0 and %t1 will have the same
11771/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011772/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011773/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011774/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011775/// %t2 = load i32* %t1
11776///
11777static bool equivalentAddressValues(Value *A, Value *B) {
11778 // Test if the values are trivially equivalent.
11779 if (A == B) return true;
11780
11781 // Test if the values come form identical arithmetic instructions.
11782 if (isa<BinaryOperator>(A) ||
11783 isa<CastInst>(A) ||
11784 isa<PHINode>(A) ||
11785 isa<GetElementPtrInst>(A))
11786 if (Instruction *BI = dyn_cast<Instruction>(B))
11787 if (cast<Instruction>(A)->isIdenticalTo(BI))
11788 return true;
11789
11790 // Otherwise they may not be equivalent.
11791 return false;
11792}
11793
Dale Johannesen4945c652009-03-03 21:26:39 +000011794// If this instruction has two uses, one of which is a llvm.dbg.declare,
11795// return the llvm.dbg.declare.
11796DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11797 if (!V->hasNUses(2))
11798 return 0;
11799 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11800 UI != E; ++UI) {
11801 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11802 return DI;
11803 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11804 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11805 return DI;
11806 }
11807 }
11808 return 0;
11809}
11810
Chris Lattner2f503e62005-01-31 05:36:43 +000011811Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11812 Value *Val = SI.getOperand(0);
11813 Value *Ptr = SI.getOperand(1);
11814
11815 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011816 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011817 ++NumCombined;
11818 return 0;
11819 }
Chris Lattner836692d2007-01-15 06:51:56 +000011820
11821 // If the RHS is an alloca with a single use, zapify the store, making the
11822 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011823 // If the RHS is an alloca with a two uses, the other one being a
11824 // llvm.dbg.declare, zapify the store and the declare, making the
11825 // alloca dead. We must do this to prevent declare's from affecting
11826 // codegen.
11827 if (!SI.isVolatile()) {
11828 if (Ptr->hasOneUse()) {
11829 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011830 EraseInstFromFunction(SI);
11831 ++NumCombined;
11832 return 0;
11833 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011834 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11835 if (isa<AllocaInst>(GEP->getOperand(0))) {
11836 if (GEP->getOperand(0)->hasOneUse()) {
11837 EraseInstFromFunction(SI);
11838 ++NumCombined;
11839 return 0;
11840 }
11841 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11842 EraseInstFromFunction(*DI);
11843 EraseInstFromFunction(SI);
11844 ++NumCombined;
11845 return 0;
11846 }
11847 }
11848 }
11849 }
11850 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11851 EraseInstFromFunction(*DI);
11852 EraseInstFromFunction(SI);
11853 ++NumCombined;
11854 return 0;
11855 }
Chris Lattner836692d2007-01-15 06:51:56 +000011856 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011857
Dan Gohman9941f742007-07-20 16:34:21 +000011858 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011859 if (TD) {
11860 unsigned KnownAlign =
11861 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11862 if (KnownAlign >
11863 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11864 SI.getAlignment()))
11865 SI.setAlignment(KnownAlign);
11866 }
Dan Gohman9941f742007-07-20 16:34:21 +000011867
Dale Johannesenacb51a32009-03-03 01:43:03 +000011868 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011869 // stores to the same location, separated by a few arithmetic operations. This
11870 // situation often occurs with bitfield accesses.
11871 BasicBlock::iterator BBI = &SI;
11872 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11873 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011874 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011875 // Don't count debug info directives, lest they affect codegen,
11876 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11877 // It is necessary for correctness to skip those that feed into a
11878 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011879 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011880 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011881 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011882 continue;
11883 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011884
11885 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11886 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011887 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11888 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011889 ++NumDeadStore;
11890 ++BBI;
11891 EraseInstFromFunction(*PrevSI);
11892 continue;
11893 }
11894 break;
11895 }
11896
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011897 // If this is a load, we have to stop. However, if the loaded value is from
11898 // the pointer we're loading and is producing the pointer we're storing,
11899 // then *this* store is dead (X = load P; store X -> P).
11900 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011901 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11902 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011903 EraseInstFromFunction(SI);
11904 ++NumCombined;
11905 return 0;
11906 }
11907 // Otherwise, this is a load from some other location. Stores before it
11908 // may not be dead.
11909 break;
11910 }
11911
Chris Lattner9ca96412006-02-08 03:25:32 +000011912 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011913 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011914 break;
11915 }
11916
11917
11918 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011919
11920 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011921 if (isa<ConstantPointerNull>(Ptr) &&
11922 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011923 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011924 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011925 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011926 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011927 ++NumCombined;
11928 }
11929 return 0; // Do not modify these!
11930 }
11931
11932 // store undef, Ptr -> noop
11933 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011934 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011935 ++NumCombined;
11936 return 0;
11937 }
11938
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011939 // If the pointer destination is a cast, see if we can fold the cast into the
11940 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011941 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011942 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11943 return Res;
11944 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011945 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011946 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11947 return Res;
11948
Chris Lattner408902b2005-09-12 23:23:25 +000011949
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011950 // If this store is the last instruction in the basic block (possibly
11951 // excepting debug info instructions and the pointer bitcasts that feed
11952 // into them), and if the block ends with an unconditional branch, try
11953 // to move it to the successor block.
11954 BBI = &SI;
11955 do {
11956 ++BBI;
11957 } while (isa<DbgInfoIntrinsic>(BBI) ||
11958 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011959 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011960 if (BI->isUnconditional())
11961 if (SimplifyStoreAtEndOfBlock(SI))
11962 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011963
Chris Lattner2f503e62005-01-31 05:36:43 +000011964 return 0;
11965}
11966
Chris Lattner3284d1f2007-04-15 00:07:55 +000011967/// SimplifyStoreAtEndOfBlock - Turn things like:
11968/// if () { *P = v1; } else { *P = v2 }
11969/// into a phi node with a store in the successor.
11970///
Chris Lattner31755a02007-04-15 01:02:18 +000011971/// Simplify things like:
11972/// *P = v1; if () { *P = v2; }
11973/// into a phi node with a store in the successor.
11974///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011975bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11976 BasicBlock *StoreBB = SI.getParent();
11977
11978 // Check to see if the successor block has exactly two incoming edges. If
11979 // so, see if the other predecessor contains a store to the same location.
11980 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011981 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011982
11983 // Determine whether Dest has exactly two predecessors and, if so, compute
11984 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011985 pred_iterator PI = pred_begin(DestBB);
11986 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011987 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011988 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011989 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011990 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011991 return false;
11992
11993 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011994 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011995 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011996 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011997 }
Chris Lattner31755a02007-04-15 01:02:18 +000011998 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011999 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012000
12001 // Bail out if all the relevant blocks aren't distinct (this can happen,
12002 // for example, if SI is in an infinite loop)
12003 if (StoreBB == DestBB || OtherBB == DestBB)
12004 return false;
12005
Chris Lattner31755a02007-04-15 01:02:18 +000012006 // Verify that the other block ends in a branch and is not otherwise empty.
12007 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012008 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012009 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012010 return false;
12011
Chris Lattner31755a02007-04-15 01:02:18 +000012012 // If the other block ends in an unconditional branch, check for the 'if then
12013 // else' case. there is an instruction before the branch.
12014 StoreInst *OtherStore = 0;
12015 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012016 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012017 // Skip over debugging info.
12018 while (isa<DbgInfoIntrinsic>(BBI) ||
12019 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12020 if (BBI==OtherBB->begin())
12021 return false;
12022 --BBI;
12023 }
12024 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012025 OtherStore = dyn_cast<StoreInst>(BBI);
12026 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12027 return false;
12028 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012029 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012030 // destinations is StoreBB, then we have the if/then case.
12031 if (OtherBr->getSuccessor(0) != StoreBB &&
12032 OtherBr->getSuccessor(1) != StoreBB)
12033 return false;
12034
12035 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012036 // if/then triangle. See if there is a store to the same ptr as SI that
12037 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012038 for (;; --BBI) {
12039 // Check to see if we find the matching store.
12040 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12041 if (OtherStore->getOperand(1) != SI.getOperand(1))
12042 return false;
12043 break;
12044 }
Eli Friedman6903a242008-06-13 22:02:12 +000012045 // If we find something that may be using or overwriting the stored
12046 // value, or if we run out of instructions, we can't do the xform.
12047 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012048 BBI == OtherBB->begin())
12049 return false;
12050 }
12051
12052 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012053 // make sure nothing reads or overwrites the stored value in
12054 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012055 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12056 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012057 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012058 return false;
12059 }
12060 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012061
Chris Lattner31755a02007-04-15 01:02:18 +000012062 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012063 Value *MergedVal = OtherStore->getOperand(0);
12064 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012065 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012066 PN->reserveOperandSpace(2);
12067 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012068 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12069 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012070 }
12071
12072 // Advance to a place where it is safe to insert the new store and
12073 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012074 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012075 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12076 OtherStore->isVolatile()), *BBI);
12077
12078 // Nuke the old stores.
12079 EraseInstFromFunction(SI);
12080 EraseInstFromFunction(*OtherStore);
12081 ++NumCombined;
12082 return true;
12083}
12084
Chris Lattner2f503e62005-01-31 05:36:43 +000012085
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012086Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12087 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012088 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012089 BasicBlock *TrueDest;
12090 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012091 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012092 !isa<Constant>(X)) {
12093 // Swap Destinations and condition...
12094 BI.setCondition(X);
12095 BI.setSuccessor(0, FalseDest);
12096 BI.setSuccessor(1, TrueDest);
12097 return &BI;
12098 }
12099
Reid Spencere4d87aa2006-12-23 06:05:41 +000012100 // Cannonicalize fcmp_one -> fcmp_oeq
12101 FCmpInst::Predicate FPred; Value *Y;
12102 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012103 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012104 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12105 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12106 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012107 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012108 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012109 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012110 // Swap Destinations and condition...
12111 BI.setCondition(NewSCC);
12112 BI.setSuccessor(0, FalseDest);
12113 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012114 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012115 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012116 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012117 return &BI;
12118 }
12119
12120 // Cannonicalize icmp_ne -> icmp_eq
12121 ICmpInst::Predicate IPred;
12122 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012123 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012124 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12125 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12126 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12127 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012128 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012129 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012130 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012131 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012132 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012133 BI.setSuccessor(0, FalseDest);
12134 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012135 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012136 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012137 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012138 return &BI;
12139 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012140
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012141 return 0;
12142}
Chris Lattner0864acf2002-11-04 16:18:53 +000012143
Chris Lattner46238a62004-07-03 00:26:11 +000012144Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12145 Value *Cond = SI.getCondition();
12146 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12147 if (I->getOpcode() == Instruction::Add)
12148 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12149 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12150 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012151 SI.setOperand(i,
12152 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012153 AddRHS));
12154 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012155 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012156 return &SI;
12157 }
12158 }
12159 return 0;
12160}
12161
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012162Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012163 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012164
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012165 if (!EV.hasIndices())
12166 return ReplaceInstUsesWith(EV, Agg);
12167
12168 if (Constant *C = dyn_cast<Constant>(Agg)) {
12169 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012170 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012171
12172 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012173 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012174
12175 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12176 // Extract the element indexed by the first index out of the constant
12177 Value *V = C->getOperand(*EV.idx_begin());
12178 if (EV.getNumIndices() > 1)
12179 // Extract the remaining indices out of the constant indexed by the
12180 // first index
12181 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12182 else
12183 return ReplaceInstUsesWith(EV, V);
12184 }
12185 return 0; // Can't handle other constants
12186 }
12187 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12188 // We're extracting from an insertvalue instruction, compare the indices
12189 const unsigned *exti, *exte, *insi, *inse;
12190 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12191 exte = EV.idx_end(), inse = IV->idx_end();
12192 exti != exte && insi != inse;
12193 ++exti, ++insi) {
12194 if (*insi != *exti)
12195 // The insert and extract both reference distinctly different elements.
12196 // This means the extract is not influenced by the insert, and we can
12197 // replace the aggregate operand of the extract with the aggregate
12198 // operand of the insert. i.e., replace
12199 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12200 // %E = extractvalue { i32, { i32 } } %I, 0
12201 // with
12202 // %E = extractvalue { i32, { i32 } } %A, 0
12203 return ExtractValueInst::Create(IV->getAggregateOperand(),
12204 EV.idx_begin(), EV.idx_end());
12205 }
12206 if (exti == exte && insi == inse)
12207 // Both iterators are at the end: Index lists are identical. Replace
12208 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12209 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12210 // with "i32 42"
12211 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12212 if (exti == exte) {
12213 // The extract list is a prefix of the insert list. i.e. replace
12214 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12215 // %E = extractvalue { i32, { i32 } } %I, 1
12216 // with
12217 // %X = extractvalue { i32, { i32 } } %A, 1
12218 // %E = insertvalue { i32 } %X, i32 42, 0
12219 // by switching the order of the insert and extract (though the
12220 // insertvalue should be left in, since it may have other uses).
12221 Value *NewEV = InsertNewInstBefore(
12222 ExtractValueInst::Create(IV->getAggregateOperand(),
12223 EV.idx_begin(), EV.idx_end()),
12224 EV);
12225 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12226 insi, inse);
12227 }
12228 if (insi == inse)
12229 // The insert list is a prefix of the extract list
12230 // We can simply remove the common indices from the extract and make it
12231 // operate on the inserted value instead of the insertvalue result.
12232 // i.e., replace
12233 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12234 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12235 // with
12236 // %E extractvalue { i32 } { i32 42 }, 0
12237 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12238 exti, exte);
12239 }
12240 // Can't simplify extracts from other values. Note that nested extracts are
12241 // already simplified implicitely by the above (extract ( extract (insert) )
12242 // will be translated into extract ( insert ( extract ) ) first and then just
12243 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012244 return 0;
12245}
12246
Chris Lattner220b0cf2006-03-05 00:22:33 +000012247/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12248/// is to leave as a vector operation.
12249static bool CheapToScalarize(Value *V, bool isConstant) {
12250 if (isa<ConstantAggregateZero>(V))
12251 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012252 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012253 if (isConstant) return true;
12254 // If all elts are the same, we can extract.
12255 Constant *Op0 = C->getOperand(0);
12256 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12257 if (C->getOperand(i) != Op0)
12258 return false;
12259 return true;
12260 }
12261 Instruction *I = dyn_cast<Instruction>(V);
12262 if (!I) return false;
12263
12264 // Insert element gets simplified to the inserted element or is deleted if
12265 // this is constant idx extract element and its a constant idx insertelt.
12266 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12267 isa<ConstantInt>(I->getOperand(2)))
12268 return true;
12269 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12270 return true;
12271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12272 if (BO->hasOneUse() &&
12273 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12274 CheapToScalarize(BO->getOperand(1), isConstant)))
12275 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012276 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12277 if (CI->hasOneUse() &&
12278 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12279 CheapToScalarize(CI->getOperand(1), isConstant)))
12280 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012281
12282 return false;
12283}
12284
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012285/// Read and decode a shufflevector mask.
12286///
12287/// It turns undef elements into values that are larger than the number of
12288/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012289static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12290 unsigned NElts = SVI->getType()->getNumElements();
12291 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12292 return std::vector<unsigned>(NElts, 0);
12293 if (isa<UndefValue>(SVI->getOperand(2)))
12294 return std::vector<unsigned>(NElts, 2*NElts);
12295
12296 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012297 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012298 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12299 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012300 Result.push_back(NElts*2); // undef -> 8
12301 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012302 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012303 return Result;
12304}
12305
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012306/// FindScalarElement - Given a vector and an element number, see if the scalar
12307/// value is already around as a register, for example if it were inserted then
12308/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012309static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012310 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012311 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12312 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012313 unsigned Width = PTy->getNumElements();
12314 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012315 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012316
12317 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012318 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012319 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012320 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012321 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012322 return CP->getOperand(EltNo);
12323 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12324 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012325 if (!isa<ConstantInt>(III->getOperand(2)))
12326 return 0;
12327 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012328
12329 // If this is an insert to the element we are looking for, return the
12330 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012331 if (EltNo == IIElt)
12332 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012333
12334 // Otherwise, the insertelement doesn't modify the value, recurse on its
12335 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012336 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012337 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012338 unsigned LHSWidth =
12339 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012340 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012341 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012342 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012343 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012344 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012345 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012346 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012347 }
12348
12349 // Otherwise, we don't know.
12350 return 0;
12351}
12352
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012353Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012354 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012355 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012356 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012357
Dan Gohman07a96762007-07-16 14:29:03 +000012358 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012359 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012360 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012361
Reid Spencer9d6565a2007-02-15 02:26:10 +000012362 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012363 // If vector val is constant with all elements the same, replace EI with
12364 // that element. When the elements are not identical, we cannot replace yet
12365 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012366 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012367 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012368 if (C->getOperand(i) != op0) {
12369 op0 = 0;
12370 break;
12371 }
12372 if (op0)
12373 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012374 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012375
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012376 // If extracting a specified index from the vector, see if we can recursively
12377 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012378 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012379 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012380 unsigned VectorWidth =
12381 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012382
12383 // If this is extracting an invalid index, turn this into undef, to avoid
12384 // crashing the code below.
12385 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012386 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012387
Chris Lattner867b99f2006-10-05 06:55:50 +000012388 // This instruction only demands the single element from the input vector.
12389 // If the input vector has a single use, simplify it based on this use
12390 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012391 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012392 APInt UndefElts(VectorWidth, 0);
12393 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012394 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012395 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012396 EI.setOperand(0, V);
12397 return &EI;
12398 }
12399 }
12400
Owen Andersond672ecb2009-07-03 00:17:18 +000012401 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012402 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012403
12404 // If the this extractelement is directly using a bitcast from a vector of
12405 // the same number of elements, see if we can find the source element from
12406 // it. In this case, we will end up needing to bitcast the scalars.
12407 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12408 if (const VectorType *VT =
12409 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12410 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012411 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12412 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012413 return new BitCastInst(Elt, EI.getType());
12414 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012415 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012416
Chris Lattner73fa49d2006-05-25 22:53:38 +000012417 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012418 if (I->hasOneUse()) {
12419 // Push extractelement into predecessor operation if legal and
12420 // profitable to do so
12421 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012422 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12423 if (CheapToScalarize(BO, isConstantElt)) {
12424 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012425 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012426 EI.getName()+".lhs");
12427 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012428 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012429 EI.getName()+".rhs");
12430 InsertNewInstBefore(newEI0, EI);
12431 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012432 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012433 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012434 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012435 unsigned AS =
12436 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012437 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012438 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012439 GetElementPtrInst *GEP =
12440 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012441 InsertNewInstBefore(GEP, EI);
12442 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012443 }
12444 }
12445 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12446 // Extracting the inserted element?
12447 if (IE->getOperand(2) == EI.getOperand(1))
12448 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12449 // If the inserted and extracted elements are constants, they must not
12450 // be the same value, extract from the pre-inserted value instead.
12451 if (isa<Constant>(IE->getOperand(2)) &&
12452 isa<Constant>(EI.getOperand(1))) {
12453 AddUsesToWorkList(EI);
12454 EI.setOperand(0, IE->getOperand(0));
12455 return &EI;
12456 }
12457 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12458 // If this is extracting an element from a shufflevector, figure out where
12459 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012460 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12461 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012462 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012463 unsigned LHSWidth =
12464 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12465
12466 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012467 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012468 else if (SrcIdx < LHSWidth*2) {
12469 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012470 Src = SVI->getOperand(1);
12471 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012472 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012473 }
Eric Christophera3500da2009-07-25 02:28:41 +000012474 return ExtractElementInst::Create(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +000012475 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012476 }
12477 }
Eli Friedman2451a642009-07-18 23:06:53 +000012478 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012479 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012480 return 0;
12481}
12482
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012483/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12484/// elements from either LHS or RHS, return the shuffle mask and true.
12485/// Otherwise, return false.
12486static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012487 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012488 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012489 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12490 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012491 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012492
12493 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012494 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012495 return true;
12496 } else if (V == LHS) {
12497 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012498 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012499 return true;
12500 } else if (V == RHS) {
12501 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012502 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012503 return true;
12504 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12505 // If this is an insert of an extract from some other vector, include it.
12506 Value *VecOp = IEI->getOperand(0);
12507 Value *ScalarOp = IEI->getOperand(1);
12508 Value *IdxOp = IEI->getOperand(2);
12509
Chris Lattnerd929f062006-04-27 21:14:21 +000012510 if (!isa<ConstantInt>(IdxOp))
12511 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012512 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012513
12514 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12515 // Okay, we can handle this if the vector we are insertinting into is
12516 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012517 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012518 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012519 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012520 return true;
12521 }
12522 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12523 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012524 EI->getOperand(0)->getType() == V->getType()) {
12525 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012526 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012527
12528 // This must be extracting from either LHS or RHS.
12529 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12530 // Okay, we can handle this if the vector we are insertinting into is
12531 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012532 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012533 // If so, update the mask to reflect the inserted value.
12534 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012535 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012536 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012537 } else {
12538 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012539 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012540 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012541
12542 }
12543 return true;
12544 }
12545 }
12546 }
12547 }
12548 }
12549 // TODO: Handle shufflevector here!
12550
12551 return false;
12552}
12553
12554/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12555/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12556/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012557static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012558 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012559 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012560 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012561 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012562 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012563
12564 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012565 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012566 return V;
12567 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012568 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012569 return V;
12570 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12571 // If this is an insert of an extract from some other vector, include it.
12572 Value *VecOp = IEI->getOperand(0);
12573 Value *ScalarOp = IEI->getOperand(1);
12574 Value *IdxOp = IEI->getOperand(2);
12575
12576 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12577 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12578 EI->getOperand(0)->getType() == V->getType()) {
12579 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012580 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12581 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012582
12583 // Either the extracted from or inserted into vector must be RHSVec,
12584 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012585 if (EI->getOperand(0) == RHS || RHS == 0) {
12586 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012587 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012588 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012589 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012590 return V;
12591 }
12592
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012593 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012594 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12595 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012596 // Everything but the extracted element is replaced with the RHS.
12597 for (unsigned i = 0; i != NumElts; ++i) {
12598 if (i != InsertedIdx)
Owen Andersoneed707b2009-07-24 23:12:02 +000012599 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012600 }
12601 return V;
12602 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012603
12604 // If this insertelement is a chain that comes from exactly these two
12605 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012606 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12607 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012608 return EI->getOperand(0);
12609
Chris Lattnerefb47352006-04-15 01:39:45 +000012610 }
12611 }
12612 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012613 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012614
12615 // Otherwise, can't do anything fancy. Return an identity vector.
12616 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012617 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012618 return V;
12619}
12620
12621Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12622 Value *VecOp = IE.getOperand(0);
12623 Value *ScalarOp = IE.getOperand(1);
12624 Value *IdxOp = IE.getOperand(2);
12625
Chris Lattner599ded12007-04-09 01:11:16 +000012626 // Inserting an undef or into an undefined place, remove this.
12627 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12628 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012629
Chris Lattnerefb47352006-04-15 01:39:45 +000012630 // If the inserted element was extracted from some other vector, and if the
12631 // indexes are constant, try to turn this into a shufflevector operation.
12632 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12633 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12634 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012635 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012636 unsigned ExtractedIdx =
12637 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012638 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012639
12640 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12641 return ReplaceInstUsesWith(IE, VecOp);
12642
12643 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012644 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012645
12646 // If we are extracting a value from a vector, then inserting it right
12647 // back into the same place, just use the input vector.
12648 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12649 return ReplaceInstUsesWith(IE, VecOp);
12650
12651 // We could theoretically do this for ANY input. However, doing so could
12652 // turn chains of insertelement instructions into a chain of shufflevector
12653 // instructions, and right now we do not merge shufflevectors. As such,
12654 // only do this in a situation where it is clear that there is benefit.
12655 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12656 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12657 // the values of VecOp, except then one read from EIOp0.
12658 // Build a new shuffle mask.
12659 std::vector<Constant*> Mask;
12660 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012661 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012662 else {
12663 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneed707b2009-07-24 23:12:02 +000012664 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012665 NumVectorElts));
12666 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012667 Mask[InsertedIdx] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012668 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012669 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012670 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012671 }
12672
12673 // If this insertelement isn't used by some other insertelement, turn it
12674 // (and any insertelements it points to), into one big shuffle.
12675 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12676 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012677 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012678 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12679 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012680 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012681 return new ShuffleVectorInst(LHS, RHS,
12682 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012683 }
12684 }
12685 }
12686
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012687 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12688 APInt UndefElts(VWidth, 0);
12689 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12690 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12691 return &IE;
12692
Chris Lattnerefb47352006-04-15 01:39:45 +000012693 return 0;
12694}
12695
12696
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012697Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12698 Value *LHS = SVI.getOperand(0);
12699 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012700 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012701
12702 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012703
Chris Lattner867b99f2006-10-05 06:55:50 +000012704 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012705 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012706 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012707
Dan Gohman488fbfc2008-09-09 18:11:14 +000012708 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012709
12710 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12711 return 0;
12712
Evan Cheng388df622009-02-03 10:05:09 +000012713 APInt UndefElts(VWidth, 0);
12714 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12715 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012716 LHS = SVI.getOperand(0);
12717 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012718 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012719 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012720
Chris Lattner863bcff2006-05-25 23:48:38 +000012721 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12722 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12723 if (LHS == RHS || isa<UndefValue>(LHS)) {
12724 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012725 // shuffle(undef,undef,mask) -> undef.
12726 return ReplaceInstUsesWith(SVI, LHS);
12727 }
12728
Chris Lattner863bcff2006-05-25 23:48:38 +000012729 // Remap any references to RHS to use LHS.
12730 std::vector<Constant*> Elts;
12731 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012732 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012733 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012734 else {
12735 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012736 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012737 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012738 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012739 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012740 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneed707b2009-07-24 23:12:02 +000012741 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012742 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012743 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012744 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012745 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012746 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12747 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012748 LHS = SVI.getOperand(0);
12749 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012750 MadeChange = true;
12751 }
12752
Chris Lattner7b2e27922006-05-26 00:29:06 +000012753 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012754 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012755
Chris Lattner863bcff2006-05-25 23:48:38 +000012756 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12757 if (Mask[i] >= e*2) continue; // Ignore undef values.
12758 // Is this an identity shuffle of the LHS value?
12759 isLHSID &= (Mask[i] == i);
12760
12761 // Is this an identity shuffle of the RHS value?
12762 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012763 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012764
Chris Lattner863bcff2006-05-25 23:48:38 +000012765 // Eliminate identity shuffles.
12766 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12767 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012768
Chris Lattner7b2e27922006-05-26 00:29:06 +000012769 // If the LHS is a shufflevector itself, see if we can combine it with this
12770 // one without producing an unusual shuffle. Here we are really conservative:
12771 // we are absolutely afraid of producing a shuffle mask not in the input
12772 // program, because the code gen may not be smart enough to turn a merged
12773 // shuffle into two specific shuffles: it may produce worse code. As such,
12774 // we only merge two shuffles if the result is one of the two input shuffle
12775 // masks. In this case, merging the shuffles just removes one instruction,
12776 // which we know is safe. This is good for things like turning:
12777 // (splat(splat)) -> splat.
12778 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12779 if (isa<UndefValue>(RHS)) {
12780 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12781
12782 std::vector<unsigned> NewMask;
12783 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12784 if (Mask[i] >= 2*e)
12785 NewMask.push_back(2*e);
12786 else
12787 NewMask.push_back(LHSMask[Mask[i]]);
12788
12789 // If the result mask is equal to the src shuffle or this shuffle mask, do
12790 // the replacement.
12791 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012792 unsigned LHSInNElts =
12793 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012794 std::vector<Constant*> Elts;
12795 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012796 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012797 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012798 } else {
Owen Andersoneed707b2009-07-24 23:12:02 +000012799 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012800 }
12801 }
12802 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12803 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012804 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012805 }
12806 }
12807 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012808
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012809 return MadeChange ? &SVI : 0;
12810}
12811
12812
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012813
Chris Lattnerea1c4542004-12-08 23:43:58 +000012814
12815/// TryToSinkInstruction - Try to move the specified instruction from its
12816/// current block into the beginning of DestBlock, which can only happen if it's
12817/// safe to move the instruction past all of the instructions between it and the
12818/// end of its block.
12819static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12820 assert(I->hasOneUse() && "Invariants didn't hold!");
12821
Chris Lattner108e9022005-10-27 17:13:11 +000012822 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012823 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012824 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012825
Chris Lattnerea1c4542004-12-08 23:43:58 +000012826 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012827 if (isa<AllocaInst>(I) && I->getParent() ==
12828 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012829 return false;
12830
Chris Lattner96a52a62004-12-09 07:14:34 +000012831 // We can only sink load instructions if there is nothing between the load and
12832 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012833 if (I->mayReadFromMemory()) {
12834 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012835 Scan != E; ++Scan)
12836 if (Scan->mayWriteToMemory())
12837 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012838 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012839
Dan Gohman02dea8b2008-05-23 21:05:58 +000012840 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012841
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012842 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012843 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012844 ++NumSunkInst;
12845 return true;
12846}
12847
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012848
12849/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12850/// all reachable code to the worklist.
12851///
12852/// This has a couple of tricks to make the code faster and more powerful. In
12853/// particular, we constant fold and DCE instructions as we go, to avoid adding
12854/// them to the worklist (this significantly speeds up instcombine on code where
12855/// many instructions are dead or constant). Additionally, if we find a branch
12856/// whose condition is a known constant, we only visit the reachable successors.
12857///
12858static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012859 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012860 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012861 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012862 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012863 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012864
Chris Lattner2c7718a2007-03-23 19:17:18 +000012865 while (!Worklist.empty()) {
12866 BB = Worklist.back();
12867 Worklist.pop_back();
12868
12869 // We have now visited this block! If we've already been here, ignore it.
12870 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012871
12872 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012873 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12874 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012875
Chris Lattner2c7718a2007-03-23 19:17:18 +000012876 // DCE instruction if trivially dead.
12877 if (isInstructionTriviallyDead(Inst)) {
12878 ++NumDeadInst;
12879 DOUT << "IC: DCE: " << *Inst;
12880 Inst->eraseFromParent();
12881 continue;
12882 }
12883
12884 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012885 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012886 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12887 Inst->replaceAllUsesWith(C);
12888 ++NumConstProp;
12889 Inst->eraseFromParent();
12890 continue;
12891 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012892
Devang Patel7fe1dec2008-11-19 18:56:50 +000012893 // If there are two consecutive llvm.dbg.stoppoint calls then
12894 // it is likely that the optimizer deleted code in between these
12895 // two intrinsics.
12896 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12897 if (DBI_Next) {
12898 if (DBI_Prev
12899 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12900 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12901 IC.RemoveFromWorkList(DBI_Prev);
12902 DBI_Prev->eraseFromParent();
12903 }
12904 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012905 } else {
12906 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012907 }
12908
Chris Lattner2c7718a2007-03-23 19:17:18 +000012909 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012910 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012911
12912 // Recursively visit successors. If this is a branch or switch on a
12913 // constant, only visit the reachable successor.
12914 TerminatorInst *TI = BB->getTerminator();
12915 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12916 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12917 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012918 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012919 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012920 continue;
12921 }
12922 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12923 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12924 // See if this is an explicit destination.
12925 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12926 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012927 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012928 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012929 continue;
12930 }
12931
12932 // Otherwise it is the default destination.
12933 Worklist.push_back(SI->getSuccessor(0));
12934 continue;
12935 }
12936 }
12937
12938 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12939 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012940 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012941}
12942
Chris Lattnerec9c3582007-03-03 02:04:50 +000012943bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012944 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012945 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012946
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012947 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12948 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012949
Chris Lattnerb3d59702005-07-07 20:40:38 +000012950 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012951 // Do a depth-first traversal of the function, populate the worklist with
12952 // the reachable instructions. Ignore blocks that are not reachable. Keep
12953 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012954 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012955 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012956
Chris Lattnerb3d59702005-07-07 20:40:38 +000012957 // Do a quick scan over the function. If we find any blocks that are
12958 // unreachable, remove any instructions inside of them. This prevents
12959 // the instcombine code from having to deal with some bad special cases.
12960 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12961 if (!Visited.count(BB)) {
12962 Instruction *Term = BB->getTerminator();
12963 while (Term != BB->begin()) { // Remove instrs bottom-up
12964 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012965
Bill Wendlingb7427032006-11-26 09:46:52 +000012966 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012967 // A debug intrinsic shouldn't force another iteration if we weren't
12968 // going to do one without it.
12969 if (!isa<DbgInfoIntrinsic>(I)) {
12970 ++NumDeadInst;
12971 Changed = true;
12972 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012973 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012974 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012975 I->eraseFromParent();
12976 }
12977 }
12978 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012979
Chris Lattnerdbab3862007-03-02 21:28:56 +000012980 while (!Worklist.empty()) {
12981 Instruction *I = RemoveOneFromWorkList();
12982 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012983
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012984 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012985 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012986 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012987 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012988 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012989 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012990
Bill Wendlingb7427032006-11-26 09:46:52 +000012991 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012992
12993 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012994 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012995 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012996 continue;
12997 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012998
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012999 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013000 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013001 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013002
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013003 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013004 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013005 ReplaceInstUsesWith(*I, C);
13006
Chris Lattner62b14df2002-09-02 04:59:56 +000013007 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013008 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013009 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013010 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013011 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013012 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013013
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013014 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013015 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013016 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13017 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013018 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13019 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013020 if (NewC != CE) {
13021 i->set(NewC);
13022 Changed = true;
13023 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013024 }
13025
Chris Lattnerea1c4542004-12-08 23:43:58 +000013026 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013027 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013028 BasicBlock *BB = I->getParent();
13029 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13030 if (UserParent != BB) {
13031 bool UserIsSuccessor = false;
13032 // See if the user is one of our successors.
13033 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13034 if (*SI == UserParent) {
13035 UserIsSuccessor = true;
13036 break;
13037 }
13038
13039 // If the user is one of our immediate successors, and if that successor
13040 // only has us as a predecessors (we'd have to split the critical edge
13041 // otherwise), we can keep going.
13042 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13043 next(pred_begin(UserParent)) == pred_end(UserParent))
13044 // Okay, the CFG is simple enough, try to sink this instruction.
13045 Changed |= TryToSinkInstruction(I, UserParent);
13046 }
13047 }
13048
Chris Lattner8a2a3112001-12-14 16:52:21 +000013049 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013050#ifndef NDEBUG
13051 std::string OrigI;
13052#endif
13053 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013054 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013055 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013056 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013057 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013058 DOUT << "IC: Old = " << *I
13059 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013060
Chris Lattnerf523d062004-06-09 05:08:07 +000013061 // Everything uses the new instruction now.
13062 I->replaceAllUsesWith(Result);
13063
13064 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013065 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013066 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013067
Chris Lattner6934a042007-02-11 01:23:03 +000013068 // Move the name to the new instruction first.
13069 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013070
13071 // Insert the new instruction into the basic block...
13072 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013073 BasicBlock::iterator InsertPos = I;
13074
13075 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13076 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13077 ++InsertPos;
13078
13079 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013080
Chris Lattner00d51312004-05-01 23:27:23 +000013081 // Make sure that we reprocess all operands now that we reduced their
13082 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013083 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013084
Chris Lattnerf523d062004-06-09 05:08:07 +000013085 // Instructions can end up on the worklist more than once. Make sure
13086 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013087 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013088
13089 // Erase the old instruction.
13090 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013091 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013092#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013093 DOUT << "IC: Mod = " << OrigI
13094 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013095#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013096
Chris Lattner90ac28c2002-08-02 19:29:35 +000013097 // If the instruction was modified, it's possible that it is now dead.
13098 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013099 if (isInstructionTriviallyDead(I)) {
13100 // Make sure we process all operands now that we are reducing their
13101 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013102 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013103
Chris Lattner00d51312004-05-01 23:27:23 +000013104 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013105 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013106 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013107 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013108 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013109 AddToWorkList(I);
13110 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013111 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013112 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013113 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013114 }
13115 }
13116
Chris Lattnerec9c3582007-03-03 02:04:50 +000013117 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013118
13119 // Do an explicit clear, this shrinks the map if needed.
13120 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013121 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013122}
13123
Chris Lattnerec9c3582007-03-03 02:04:50 +000013124
13125bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013126 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013127 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013128
Chris Lattnerec9c3582007-03-03 02:04:50 +000013129 bool EverMadeChange = false;
13130
13131 // Iterate while there is work to do.
13132 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013133 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013134 EverMadeChange = true;
13135 return EverMadeChange;
13136}
13137
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013138FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013139 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013140}