blob: 514e91bdef32d6baea755388b86ba9983b571647 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000059#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000060#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000061#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000063#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000064#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000065#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000066#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000077 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000080 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000083 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000084 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000086 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000088
Owen Andersone922c022009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000091
Chris Lattnerdbab3862007-03-02 21:28:56 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000122 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126 }
127
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000134 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000135 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif177dd3f2008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000148 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 // Set the operand to undef to drop the use.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000151 }
152
153 return R;
154 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000155
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000157 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000158
159 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160
Chris Lattner97e52e42002-04-28 21:27:06 +0000161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000162 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000163 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000164 }
165
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000167
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000172 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000173 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000174 //
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000215
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000217 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000219 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000222 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000234 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000244 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000245 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000246 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000247 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000248 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000249 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000250 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000256 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000257
Chris Lattner9fe38862003-06-19 17:00:31 +0000258 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000259 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000260 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Chris Lattner9fe38862003-06-19 17:00:31 +0000267
Chris Lattner28977af2004-04-05 01:30:19 +0000268 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
Chris Lattner955f3312004-09-28 21:48:02 +0000272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000277 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000278 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000279 }
280
Chris Lattner0c967662004-09-24 15:21:34 +0000281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000286 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattnere2ed0572006-04-06 19:19:17 +0000288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000290
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000292 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000293 return C;
294 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Chris Lattner0c967662004-09-24 15:21:34 +0000300
Chris Lattner8b170942002-08-09 23:47:40 +0000301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000316 return &I;
317 }
Chris Lattner8b170942002-08-09 23:47:40 +0000318 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319
320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000327 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000328 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000329 return 0; // Don't do anything with FI
330 }
Chris Lattner173234a2008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000345 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000349 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000350
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner886ab6c2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng388df622009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000371
Chris Lattner4e998b22004-09-29 05:07:12 +0000372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
Chris Lattnerbac32862004-11-14 19:13:23 +0000377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Chris Lattner7da52b22006-11-01 04:51:18 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000387
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000389 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000391 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000397
Chris Lattnerafe91a52006-06-15 19:07:26 +0000398
Reid Spencerc55b2432006-12-13 18:21:21 +0000399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400
Dan Gohman6de29f82009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000405
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000406 };
407}
408
Dan Gohman844731a2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Chris Lattner4f98c562003-03-10 21:43:22 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000415static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 return 3;
421 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000425}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000426
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000430 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000431}
432
Chris Lattner4cb170c2004-02-23 06:38:22 +0000433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000439 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000440 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000441}
442
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 }
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return 0;
455}
456
Reid Spencer3da59db2006-11-27 01:05:10 +0000457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Chris Lattnera0e69692009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000475 DstTy,
476 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 Res = 0;
483
484 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000485}
486
487/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488/// in any code being generated. It does not require codegen if V is simple
489/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
Chris Lattner01575b72006-05-25 23:24:33 +0000494 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000497 return false;
498 return true;
499}
500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000503//
Chris Lattner4f98c562003-03-10 21:43:22 +0000504// 1. Order operands such that they are listed from right (least complex) to
505// left (most complex). This puts constants before unary operators before
506// binary operators.
507//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000510//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000513 if (getComplexity(Context, I.getOperand(0)) <
514 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000516
Chris Lattner4f98c562003-03-10 21:43:22 +0000517 if (!I.isAssociative()) return Changed;
518 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000522 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000523 cast<Constant>(I.getOperand(1)),
524 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 I.setOperand(0, Op->getOperand(0));
526 I.setOperand(1, Folded);
527 return true;
528 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530 isOnlyUse(Op) && isOnlyUse(Op1)) {
531 Constant *C1 = cast<Constant>(Op->getOperand(1));
532 Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000535 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000536 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 Op1->getOperand(0),
538 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000539 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000540 I.setOperand(0, New);
541 I.setOperand(1, Folded);
542 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000543 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000546}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000547
Reid Spencere4d87aa2006-12-23 06:05:41 +0000548/// SimplifyCompare - For a CmpInst this function just orders the operands
549/// so that theyare listed from right (least complex) to left (most complex).
550/// This puts constants before unary operators before binary operators.
551bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000552 if (getComplexity(Context, I.getOperand(0)) >=
553 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
Chris Lattner8d969642003-03-10 23:06:50 +0000560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000562//
Dan Gohman186a6362009-08-12 16:04:34 +0000563static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000565 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000566
Chris Lattner0ce85802004-12-14 20:08:06 +0000567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000574
Chris Lattner8d969642003-03-10 23:06:50 +0000575 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000576}
577
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Dan Gohman186a6362009-08-12 16:04:34 +0000582static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Dan Gohman186a6362009-08-12 16:04:34 +0000597static inline Value *dyn_castNotVal(Value *V) {
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))
Dan Gohman186a6362009-08-12 16:04:34 +0000603 return ConstantInt::get(C->getType(), ~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//
Dan Gohman186a6362009-08-12 16:04:34 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000613 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000614 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000615 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000617 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000618 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000619 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000620 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000621 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000622 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000623 CST = ConstantInt::get(V->getType()->getContext(),
624 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 return I->getOperand(0);
626 }
627 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000629}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000630
Reid Spencer7177c3a2007-03-25 05:33:51 +0000631/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000632static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000635}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000636/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000637static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Reid Spencere7816b52007-03-08 01:52:58 +0000664
Chris Lattner255d8912006-02-11 09:31:47 +0000665/// ShrinkDemandedConstant - Check to see if the specified operand of the
666/// specified instruction is a constant integer. If so, check to see if there
667/// are any bits set in the constant that are not demanded. If so, shrink the
668/// constant and return true.
669static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000670 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000671 assert(I && "No instruction?");
672 assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674 // If the operand is not a constant integer, nothing to do.
675 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676 if (!OpC) return false;
677
678 // If there are no bits set that aren't demanded, nothing to do.
679 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680 if ((~Demanded & OpC->getValue()) == 0)
681 return false;
682
683 // This instruction is producing bits that are not demanded. Shrink the RHS.
684 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000685 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000686 return true;
687}
688
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000689// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
690// set of known zero and one bits, compute the maximum and minimum values that
691// could have the specified known zero and known one bits, returning them in
692// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000693static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000694 const APInt& KnownOne,
695 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000696 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697 KnownZero.getBitWidth() == Min.getBitWidth() &&
698 KnownZero.getBitWidth() == Max.getBitWidth() &&
699 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000700 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000701
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000702 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703 // bit if it is unknown.
704 Min = KnownOne;
705 Max = KnownOne|UnknownBits;
706
Dan Gohman1c8491e2009-04-25 17:12:48 +0000707 if (UnknownBits.isNegative()) { // Sign bit is unknown
708 Min.set(Min.getBitWidth()-1);
709 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711}
712
713// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714// a set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000718 const APInt &KnownOne,
719 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000723 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000724 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725
726 // The minimum value is when the unknown bits are all zeros.
727 Min = KnownOne;
728 // The maximum value is when the unknown bits are all ones.
729 Max = KnownOne|UnknownBits;
730}
Chris Lattner255d8912006-02-11 09:31:47 +0000731
Chris Lattner886ab6c2009-01-31 08:15:18 +0000732/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733/// SimplifyDemandedBits knows about. See if the instruction has any
734/// properties that allow us to simplify its operands.
735bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000736 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000737 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739
740 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
741 KnownZero, KnownOne, 0);
742 if (V == 0) return false;
743 if (V == &Inst) return true;
744 ReplaceInstUsesWith(Inst, V);
745 return true;
746}
747
748/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749/// specified instruction operand if possible, updating it in place. It returns
750/// true if it made any change and false otherwise.
751bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
752 APInt &KnownZero, APInt &KnownOne,
753 unsigned Depth) {
754 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755 KnownZero, KnownOne, Depth);
756 if (NewVal == 0) return false;
757 U.set(NewVal);
758 return true;
759}
760
761
762/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000764/// that only the bits set in DemandedMask of the result of V are ever used
765/// downstream. Consequently, depending on the mask and V, it may be possible
766/// to replace V with a constant or one of its operands. In such cases, this
767/// function does the replacement and returns true. In all other cases, it
768/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000769/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000770/// to be zero in the expression. These are provided to potentially allow the
771/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772/// the expression. KnownOne and KnownZero always follow the invariant that
773/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774/// the bits in KnownOne and KnownZero may only be accurate for those bits set
775/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000777///
778/// This returns null if it did not change anything and it permits no
779/// simplification. This returns V itself if it did some simplification of V's
780/// operands based on the information about what bits are demanded. This returns
781/// some other non-null value if it found out that V is equal to another value
782/// in the context where the specified bits are demanded, but not for all users.
783Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784 APInt &KnownZero, APInt &KnownOne,
785 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000786 assert(V != 0 && "Null pointer of Value???");
787 assert(Depth <= 6 && "Limit Search Depth");
788 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000789 const Type *VTy = V->getType();
790 assert((TD || !isa<PointerType>(VTy)) &&
791 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000792 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793 (!VTy->isIntOrIntVector() ||
794 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000795 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000796 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000797 "Value *V, DemandedMask, KnownZero and KnownOne "
798 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800 // We know all of the bits for a constant!
801 KnownOne = CI->getValue() & DemandedMask;
802 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000803 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000805 if (isa<ConstantPointerNull>(V)) {
806 // We know all of the bits for a constant!
807 KnownOne.clear();
808 KnownZero = DemandedMask;
809 return 0;
810 }
811
Chris Lattner08d2cc72009-01-31 07:26:06 +0000812 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000813 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814 if (DemandedMask == 0) { // Not demanding any bits from V.
815 if (isa<UndefValue>(V))
816 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000817 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000818 }
819
Chris Lattner4598c942009-01-31 08:24:16 +0000820 if (Depth == 6) // Limit search depth.
821 return 0;
822
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000823 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 Instruction *I = dyn_cast<Instruction>(V);
827 if (!I) {
828 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829 return 0; // Only analyze instructions.
830 }
831
Chris Lattner4598c942009-01-31 08:24:16 +0000832 // If there are multiple uses of this value and we aren't at the root, then
833 // we can't do any simplifications of the operands, because DemandedMask
834 // only reflects the bits demanded by *one* of the users.
835 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000836 // Despite the fact that we can't simplify this instruction in all User's
837 // context, we can at least compute the knownzero/knownone bits, and we can
838 // do simplifications that apply to *just* the one user if we know that
839 // this instruction has a simpler value in that context.
840 if (I->getOpcode() == Instruction::And) {
841 // If either the LHS or the RHS are Zero, the result is zero.
842 ComputeMaskedBits(I->getOperand(1), DemandedMask,
843 RHSKnownZero, RHSKnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845 LHSKnownZero, LHSKnownOne, Depth+1);
846
847 // If all of the demanded bits are known 1 on one side, return the other.
848 // These bits cannot contribute to the result of the 'and' in this
849 // context.
850 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
851 (DemandedMask & ~LHSKnownZero))
852 return I->getOperand(0);
853 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
854 (DemandedMask & ~RHSKnownZero))
855 return I->getOperand(1);
856
857 // If all of the demanded bits in the inputs are known zeros, return zero.
858 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000859 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000860
861 } else if (I->getOpcode() == Instruction::Or) {
862 // We can simplify (X|Y) -> X or Y in the user's context if we know that
863 // only bits from X or Y are demanded.
864
865 // If either the LHS or the RHS are One, the result is One.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known zero on one side, return the
872 // other. These bits cannot contribute to the result of the 'or' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
875 (DemandedMask & ~LHSKnownOne))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
878 (DemandedMask & ~RHSKnownOne))
879 return I->getOperand(1);
880
881 // If all of the potentially set bits on one side are known to be set on
882 // the other side, just use the 'other' side.
883 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
884 (DemandedMask & (~RHSKnownZero)))
885 return I->getOperand(0);
886 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
887 (DemandedMask & (~LHSKnownZero)))
888 return I->getOperand(1);
889 }
890
Chris Lattner4598c942009-01-31 08:24:16 +0000891 // Compute the KnownZero/KnownOne bits to simplify things downstream.
892 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893 return 0;
894 }
895
896 // If this is the root being simplified, allow it to have multiple uses,
897 // just set the DemandedMask to all bits so that we can try to simplify the
898 // operands. This allows visitTruncInst (for example) to simplify the
899 // operand of a trunc without duplicating all the logic below.
900 if (Depth == 0 && !V->hasOneUse())
901 DemandedMask = APInt::getAllOnesValue(BitWidth);
902
Reid Spencer8cb68342007-03-12 17:25:59 +0000903 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000904 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000905 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000906 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000907 case Instruction::And:
908 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000909 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910 RHSKnownZero, RHSKnownOne, Depth+1) ||
911 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000913 return I;
914 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
915 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000916
917 // If all of the demanded bits are known 1 on one side, return the other.
918 // These bits cannot contribute to the result of the 'and'.
919 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
920 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000921 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
923 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000925
926 // If all of the demanded bits in the inputs are known zeros, return zero.
927 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000928 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000929
930 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000931 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000933
934 // Output known-1 bits are only known if set in both the LHS & RHS.
935 RHSKnownOne &= LHSKnownOne;
936 // Output known-0 are known to be clear if zero in either the LHS | RHS.
937 RHSKnownZero |= LHSKnownZero;
938 break;
939 case Instruction::Or:
940 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
942 RHSKnownZero, RHSKnownOne, Depth+1) ||
943 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 return I;
946 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
947 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // If all of the demanded bits are known zero on one side, return the other.
950 // These bits cannot contribute to the result of the 'or'.
951 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
952 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000953 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
955 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the potentially set bits on one side are known to be set on
959 // the other side, just use the 'other' side.
960 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
961 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
964 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000968 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000970
971 // Output known-0 bits are only known if clear in both the LHS & RHS.
972 RHSKnownZero &= LHSKnownZero;
973 // Output known-1 are known to be set if set in either the LHS | RHS.
974 RHSKnownOne |= LHSKnownOne;
975 break;
976 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'xor'.
987 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // Output known-0 bits are known if clear or set in both the LHS & RHS.
993 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
994 (RHSKnownOne & LHSKnownOne);
995 // Output known-1 are known to be set if set in only one of the LHS, RHS.
996 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
997 (RHSKnownOne & LHSKnownZero);
998
999 // If all of the demanded bits are known to be zero on one side or the
1000 // other, turn this into an *inclusive* or.
1001 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001004 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007 }
1008
1009 // If all of the demanded bits on one side are known, and all of the set
1010 // bits on that side are also known to be set on the other side, turn this
1011 // into an AND, as we know the bits will be cleared.
1012 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1014 // all known
1015 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001016 Constant *AndC = Constant::getIntegerValue(VTy,
1017 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001019 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001021 }
1022 }
1023
1024 // If the RHS is a constant, see if we can simplify it.
1025 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 RHSKnownZero = KnownZeroOut;
1030 RHSKnownOne = KnownOneOut;
1031 break;
1032 }
1033 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035 RHSKnownZero, RHSKnownOne, Depth+1) ||
1036 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 return I;
1039 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1040 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001041
1042 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001043 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
1047 // Only known if known in both the LHS and RHS.
1048 RHSKnownOne &= LHSKnownOne;
1049 RHSKnownZero &= LHSKnownZero;
1050 break;
1051 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001052 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001053 DemandedMask.zext(truncBf);
1054 RHSKnownZero.zext(truncBf);
1055 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001057 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001058 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 DemandedMask.trunc(BitWidth);
1060 RHSKnownZero.trunc(BitWidth);
1061 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 break;
1064 }
1065 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001066 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001068
1069 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070 if (const VectorType *SrcVTy =
1071 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073 // Don't touch a bitcast between vectors of different element counts.
1074 return false;
1075 } else
1076 // Don't touch a scalar-to-vector bitcast.
1077 return false;
1078 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079 // Don't touch a vector-to-scalar bitcast.
1080 return false;
1081
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 return I;
1085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 break;
1087 case Instruction::ZExt: {
1088 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001089 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001090
Zhou Shengd48653a2007-03-29 04:45:55 +00001091 DemandedMask.trunc(SrcBitWidth);
1092 RHSKnownZero.trunc(SrcBitWidth);
1093 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001094 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001095 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 DemandedMask.zext(BitWidth);
1098 RHSKnownZero.zext(BitWidth);
1099 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001102 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 break;
1104 }
1105 case Instruction::SExt: {
1106 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001107 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001108
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001110 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
Zhou Sheng01542f32007-03-29 02:26:30 +00001112 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 // If any of the sign extended bits are demanded, we know that the sign
1114 // bit is demanded.
1115 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001116 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Zhou Shengd48653a2007-03-29 04:45:55 +00001118 InputDemandedBits.trunc(SrcBitWidth);
1119 RHSKnownZero.trunc(SrcBitWidth);
1120 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 InputDemandedBits.zext(BitWidth);
1125 RHSKnownZero.zext(BitWidth);
1126 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001128
1129 // If the sign bit of the input is known set or clear, then we know the
1130 // top bits of the result.
1131
1132 // If the input sign bit is known zero, or if the NewBits are not demanded
1133 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 }
1141 break;
1142 }
1143 case Instruction::Add: {
1144 // Figure out what the input bits are. If the top bits of the and result
1145 // are not demanded, then the add doesn't demand them from its input
1146 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001148
1149 // If there is a constant on the RHS, there are a variety of xformations
1150 // we can do.
1151 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152 // If null, this should be simplified elsewhere. Some of the xforms here
1153 // won't work if the RHS is zero.
1154 if (RHS->isZero())
1155 break;
1156
1157 // If the top bit of the output is demanded, demand everything from the
1158 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001160
1161 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001165
1166 // If the RHS of the add has bits set that can't affect the input, reduce
1167 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001168 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
1171 // Avoid excess work.
1172 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173 break;
1174
1175 // Turn it into OR if input bits are zero.
1176 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001178 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 }
1182
1183 // We can say something about the output known-zero and known-one bits,
1184 // depending on potential carries from the input constant and the
1185 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1186 // bits set and the RHS constant is 0x01001, then we know we have a known
1187 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188
1189 // To compute this, we first compute the potential carry bits. These are
1190 // the bits which may be modified. I'm not aware of a better way to do
1191 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001193 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
1195 // Now that we know which bits have carries, compute the known-1/0 sets.
1196
1197 // Bits are known one if they are known zero in one operand and one in the
1198 // other, and there is no input carry.
1199 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1200 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201
1202 // Bits are known zero if they are known zero in both operands and there
1203 // is no input carry.
1204 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205 } else {
1206 // If the high-bits of this ADD are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 // Right fill the mask of bits for this ADD to demand the most
1210 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001211 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213 LHSKnownZero, LHSKnownOne, Depth+1) ||
1214 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001216 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 }
1218 }
1219 break;
1220 }
1221 case Instruction::Sub:
1222 // If the high-bits of this SUB are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 // Right fill the mask of bits for this SUB to demand the most
1226 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001227 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230 LHSKnownZero, LHSKnownOne, Depth+1) ||
1231 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001234 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001235 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236 // the known zeros and ones.
1237 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 break;
1239 case Instruction::Shl:
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001242 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 return I;
1246 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 RHSKnownZero <<= ShiftAmt;
1248 RHSKnownOne <<= ShiftAmt;
1249 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001250 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001251 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 }
1253 break;
1254 case Instruction::LShr:
1255 // For a logical shift right
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001258
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001260 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001263 return I;
1264 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001267 if (ShiftAmt) {
1268 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001269 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001270 RHSKnownZero |= HighBits; // high bits known zero.
1271 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 }
1273 break;
1274 case Instruction::AShr:
1275 // If this is an arithmetic shift right and only the low-bit is set, we can
1276 // always convert this into a logical shr, even if the shift amount is
1277 // variable. The low bit of the shift cannot be an input sign bit unless
1278 // the shift amount is >= the size of the datatype, which is undefined.
1279 if (DemandedMask == 1) {
1280 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001281 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001285
1286 // If the sign bit is the only bit demanded by this ashr, then there is no
1287 // need to do it, the shift doesn't change the high bit.
1288 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001292 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001293
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001296 // If any of the "high bits" are demanded, we should set the sign bit as
1297 // demanded.
1298 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001302 return I;
1303 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001305 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308
1309 // Handle the sign bits.
1310 APInt SignBit(APInt::getSignBit(BitWidth));
1311 // Adjust to where it is now in the mask.
1312 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1313
1314 // If the input sign bit is known to be zero, or if none of the top bits
1315 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001316 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 (HighBits & ~DemandedMask) == HighBits) {
1318 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323 RHSKnownOne |= HighBits;
1324 }
1325 }
1326 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001327 case Instruction::SRem:
1328 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001329 APInt RA = Rem->getValue().abs();
1330 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001331 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001333
Nick Lewycky8e394322008-11-02 02:41:50 +00001334 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001335 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001337 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001338 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001339
1340 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342
1343 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001344
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 }
1347 }
1348 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001349 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001350 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353 KnownZero2, KnownOne2, Depth+1) ||
1354 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001355 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001357
Chris Lattner455e9ab2009-01-21 18:09:24 +00001358 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001359 Leaders = std::max(Leaders,
1360 KnownZero2.countLeadingOnes());
1361 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001363 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001364 case Instruction::Call:
1365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366 switch (II->getIntrinsicID()) {
1367 default: break;
1368 case Intrinsic::bswap: {
1369 // If the only bits demanded come from one byte of the bswap result,
1370 // just shift the input byte into position to eliminate the bswap.
1371 unsigned NLZ = DemandedMask.countLeadingZeros();
1372 unsigned NTZ = DemandedMask.countTrailingZeros();
1373
1374 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1375 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1376 // have 14 leading zeros, round to 8.
1377 NLZ &= ~7;
1378 NTZ &= ~7;
1379 // If we need exactly one byte, we can do this transformation.
1380 if (BitWidth-NLZ-NTZ == 8) {
1381 unsigned ResultBit = NTZ;
1382 unsigned InputBit = BitWidth-NTZ-8;
1383
1384 // Replace this with either a left or right shift to get the byte into
1385 // the right place.
1386 Instruction *NewVal;
1387 if (InputBit > ResultBit)
1388 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001389 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001390 else
1391 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001392 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001393 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001394 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001395 }
1396
1397 // TODO: Could compute known zero/one bits based on the input.
1398 break;
1399 }
1400 }
1401 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001402 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001403 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001404 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001405
1406 // If the client is only demanding bits that we know, return the known
1407 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001408 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 return false;
1411}
1412
Chris Lattner867b99f2006-10-05 06:55:50 +00001413
Mon P Wangaeb06d22008-11-10 04:46:22 +00001414/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001415/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001416/// actually used by the caller. This method analyzes which elements of the
1417/// operand are undef and returns that information in UndefElts.
1418///
1419/// If the information about demanded elements can be used to simplify the
1420/// operation, the operation is simplified, then the resultant value is
1421/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001422Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001424 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001425 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001426 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001427 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001428
1429 if (isa<UndefValue>(V)) {
1430 // If the entire vector is undefined, just return this info.
1431 UndefElts = EltMask;
1432 return 0;
1433 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001435 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001436 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001437
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001439 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001441 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001442
1443 std::vector<Constant*> Elts;
1444 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001445 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001447 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1449 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001450 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 } else { // Otherwise, defined.
1452 Elts.push_back(CP->getOperand(i));
1453 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001454
Chris Lattner867b99f2006-10-05 06:55:50 +00001455 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001456 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 return NewCP != CP ? NewCP : 0;
1458 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001459 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001461
1462 // Check if this is identity. If so, return 0 since we are not simplifying
1463 // anything.
1464 if (DemandedElts == ((1ULL << VWidth) -1))
1465 return 0;
1466
Reid Spencer9d6565a2007-02-15 02:26:10 +00001467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001468 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001469 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001471 for (unsigned i = 0; i != VWidth; ++i) {
1472 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473 Elts.push_back(Elt);
1474 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001476 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 }
1478
Dan Gohman488fbfc2008-09-09 18:11:14 +00001479 // Limit search depth.
1480 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001481 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001482
1483 // If multiple users are using the root value, procede with
1484 // simplification conservatively assuming that all elements
1485 // are needed.
1486 if (!V->hasOneUse()) {
1487 // Quit if we find multiple users of a non-root value though.
1488 // They'll be handled when it's their turn to be visited by
1489 // the main instcombine process.
1490 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001492 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001493
1494 // Conservatively assume that all elements are needed.
1495 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001496 }
1497
1498 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001499 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001500
1501 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001502 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 Value *TmpV;
1504 switch (I->getOpcode()) {
1505 default: break;
1506
1507 case Instruction::InsertElement: {
1508 // If this is a variable index, we don't know which element it overwrites.
1509 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001510 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 if (Idx == 0) {
1512 // Note that we can't propagate undef elt info, because we don't know
1513 // which elt is getting updated.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts2, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 break;
1518 }
1519
1520 // If this is inserting an element that isn't demanded, remove this
1521 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001522 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001523 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 return AddSoonDeadInstToWorklist(*I, 0);
1525
1526 // Otherwise, the element inserted overwrites whatever was there, so the
1527 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001528 APInt DemandedElts2 = DemandedElts;
1529 DemandedElts2.clear(IdxNo);
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 UndefElts, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001535 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001536 break;
1537 }
1538 case Instruction::ShuffleVector: {
1539 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001540 uint64_t LHSVWidth =
1541 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001542 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001543 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001544 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001545 unsigned MaskVal = Shuffle->getMaskValue(i);
1546 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001547 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001548 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001549 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001550 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001551 else
Evan Cheng388df622009-02-03 10:05:09 +00001552 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001553 }
1554 }
1555 }
1556
Nate Begeman7b254672009-02-11 22:36:25 +00001557 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001559 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
Nate Begeman7b254672009-02-11 22:36:25 +00001562 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564 UndefElts3, Depth+1);
1565 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567 bool NewUndefElts = false;
1568 for (unsigned i = 0; i < VWidth; i++) {
1569 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001570 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001571 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001572 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001573 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001574 NewUndefElts = true;
1575 UndefElts.set(i);
1576 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001578 if (UndefElts3[MaskVal - LHSVWidth]) {
1579 NewUndefElts = true;
1580 UndefElts.set(i);
1581 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 }
1583 }
1584
1585 if (NewUndefElts) {
1586 // Add additional discovered undefs.
1587 std::vector<Constant*> Elts;
1588 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001589 if (UndefElts[i])
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001590 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 else
Owen Andersoneed707b2009-07-24 23:12:02 +00001592 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 Shuffle->getMaskValue(i)));
1594 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001595 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001596 MadeChange = true;
1597 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001598 break;
1599 }
Chris Lattner69878332007-04-14 22:29:23 +00001600 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001601 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001602 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603 if (!VTy) break;
1604 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001605 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001606 unsigned Ratio;
1607
1608 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001609 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001610 // elements as are demanded of us.
1611 Ratio = 1;
1612 InputDemandedElts = DemandedElts;
1613 } else if (VWidth > InVWidth) {
1614 // Untested so far.
1615 break;
1616
1617 // If there are more elements in the result than there are in the source,
1618 // then an input element is live if any of the corresponding output
1619 // elements are live.
1620 Ratio = VWidth/InVWidth;
1621 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001622 if (DemandedElts[OutIdx])
1623 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001624 }
1625 } else {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the source than there are in the result,
1630 // then an input element is live if the corresponding output element is
1631 // live.
1632 Ratio = InVWidth/VWidth;
1633 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001634 if (DemandedElts[InIdx/Ratio])
1635 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001636 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001637
Chris Lattner69878332007-04-14 22:29:23 +00001638 // div/rem demand all inputs, because they don't want divide by zero.
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640 UndefElts2, Depth+1);
1641 if (TmpV) {
1642 I->setOperand(0, TmpV);
1643 MadeChange = true;
1644 }
1645
1646 UndefElts = UndefElts2;
1647 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001648 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001649 // If there are more elements in the result than there are in the source,
1650 // then an output element is undef if the corresponding input element is
1651 // undef.
1652 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001653 if (UndefElts2[OutIdx/Ratio])
1654 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001655 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001656 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001657 // If there are more elements in the source than there are in the result,
1658 // then a result element is undef if all of the corresponding input
1659 // elements are undef.
1660 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001662 if (!UndefElts2[InIdx]) // Not undef?
1663 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001664 }
1665 break;
1666 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 case Instruction::Add:
1671 case Instruction::Sub:
1672 case Instruction::Mul:
1673 // div/rem demand all inputs, because they don't want divide by zero.
1674 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675 UndefElts, Depth+1);
1676 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678 UndefElts2, Depth+1);
1679 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680
1681 // Output elements are undefined if both are undefined. Consider things
1682 // like undef&0. The result is known zero, not undef.
1683 UndefElts &= UndefElts2;
1684 break;
1685
1686 case Instruction::Call: {
1687 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688 if (!II) break;
1689 switch (II->getIntrinsicID()) {
1690 default: break;
1691
1692 // Binary vector operations that work column-wise. A dest element is a
1693 // function of the corresponding input elements from the two inputs.
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse_mul_ss:
1696 case Intrinsic::x86_sse_min_ss:
1697 case Intrinsic::x86_sse_max_ss:
1698 case Intrinsic::x86_sse2_sub_sd:
1699 case Intrinsic::x86_sse2_mul_sd:
1700 case Intrinsic::x86_sse2_min_sd:
1701 case Intrinsic::x86_sse2_max_sd:
1702 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709 // If only the low elt is demanded and this is a scalarizable intrinsic,
1710 // scalarize it now.
1711 if (DemandedElts == 1) {
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714 case Intrinsic::x86_sse_sub_ss:
1715 case Intrinsic::x86_sse_mul_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 // TODO: Lower MIN/MAX/ABS/etc
1719 Value *LHS = II->getOperand(1);
1720 Value *RHS = II->getOperand(2);
1721 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001722 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001723 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001724 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001725 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001726
1727 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001728 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001731 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001732 II->getName()), *II);
1733 break;
1734 case Intrinsic::x86_sse_mul_ss:
1735 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001736 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001737 II->getName()), *II);
1738 break;
1739 }
1740
1741 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001742 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001743 UndefValue::get(II->getType()), TmpV,
Owen Andersoneed707b2009-07-24 23:12:02 +00001744 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001745 InsertNewInstBefore(New, *II);
1746 AddSoonDeadInstToWorklist(*II, 0);
1747 return New;
1748 }
1749 }
1750
1751 // Output elements are undefined if both are undefined. Consider things
1752 // like undef&0. The result is known zero, not undef.
1753 UndefElts &= UndefElts2;
1754 break;
1755 }
1756 break;
1757 }
1758 }
1759 return MadeChange ? I : 0;
1760}
1761
Dan Gohman45b4e482008-05-19 22:14:15 +00001762
Chris Lattner564a7272003-08-13 19:01:45 +00001763/// AssociativeOpt - Perform an optimization on an associative operator. This
1764/// function is designed to check a chain of associative operators for a
1765/// potential to apply a certain optimization. Since the optimization may be
1766/// applicable if the expression was reassociated, this checks the chain, then
1767/// reassociates the expression as necessary to expose the optimization
1768/// opportunity. This makes use of a special Functor, which must define
1769/// 'shouldApply' and 'apply' methods.
1770///
1771template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001772static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001773 unsigned Opcode = Root.getOpcode();
1774 Value *LHS = Root.getOperand(0);
1775
1776 // Quick check, see if the immediate LHS matches...
1777 if (F.shouldApply(LHS))
1778 return F.apply(Root);
1779
1780 // Otherwise, if the LHS is not of the same opcode as the root, return.
1781 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001782 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001783 // Should we apply this transform to the RHS?
1784 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786 // If not to the RHS, check to see if we should apply to the LHS...
1787 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1789 ShouldApply = true;
1790 }
1791
1792 // If the functor wants to apply the optimization to the RHS of LHSI,
1793 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001795 // Now all of the instructions are in the current basic block, go ahead
1796 // and perform the reassociation.
1797 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799 // First move the selected RHS to the LHS of the root...
1800 Root.setOperand(0, LHSI->getOperand(1));
1801
1802 // Make what used to be the LHS of the root be the user of the root...
1803 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001804 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001805 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001806 return 0;
1807 }
Chris Lattner65725312004-04-16 18:08:07 +00001808 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001809 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001810 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001811 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001812 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001813
1814 // Now propagate the ExtraOperand down the chain of instructions until we
1815 // get to LHSI.
1816 while (TmpLHSI != LHSI) {
1817 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001818 // Move the instruction to immediately before the chain we are
1819 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001820 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001821 ARI = NextLHSI;
1822
Chris Lattner564a7272003-08-13 19:01:45 +00001823 Value *NextOp = NextLHSI->getOperand(1);
1824 NextLHSI->setOperand(1, ExtraOperand);
1825 TmpLHSI = NextLHSI;
1826 ExtraOperand = NextOp;
1827 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001828
Chris Lattner564a7272003-08-13 19:01:45 +00001829 // Now that the instructions are reassociated, have the functor perform
1830 // the transformation...
1831 return F.apply(Root);
1832 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001833
Chris Lattner564a7272003-08-13 19:01:45 +00001834 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835 }
1836 return 0;
1837}
1838
Dan Gohman844731a2008-05-13 00:00:25 +00001839namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001840
Nick Lewycky02d639f2008-05-23 04:34:58 +00001841// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001842struct AddRHS {
1843 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001844 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001845 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001847 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001848 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001849 }
1850};
1851
1852// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853// iff C1&C2 == 0
1854struct AddMaskingAnd {
1855 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001856 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001857 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001858 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001859 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001860 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001861 }
1862 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001863 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001864 }
1865};
1866
Dan Gohman844731a2008-05-13 00:00:25 +00001867}
1868
Chris Lattner6e7ba452005-01-01 16:22:27 +00001869static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001870 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001871 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001872
Reid Spencer3da59db2006-11-27 01:05:10 +00001873 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001874 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001875 }
1876
Chris Lattner2eefe512004-04-09 19:05:30 +00001877 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001878 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1879 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001880
Chris Lattner2eefe512004-04-09 19:05:30 +00001881 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1882 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001883 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1884 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001885 }
1886
1887 Value *Op0 = SO, *Op1 = ConstOperand;
1888 if (!ConstIsRHS)
1889 std::swap(Op0, Op1);
1890 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001892 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001893 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001894 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1895 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001896 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001897 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001898 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001899 return IC->InsertNewInstBefore(New, I);
1900}
1901
1902// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1903// constant as the other operand, try to fold the binary operator into the
1904// select arguments. This also works for Cast instructions, which obviously do
1905// not have a second operand.
1906static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1907 InstCombiner *IC) {
1908 // Don't modify shared select instructions
1909 if (!SI->hasOneUse()) return 0;
1910 Value *TV = SI->getOperand(1);
1911 Value *FV = SI->getOperand(2);
1912
1913 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001914 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001915 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001916
Chris Lattner6e7ba452005-01-01 16:22:27 +00001917 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1918 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1919
Gabor Greif051a9502008-04-06 20:25:17 +00001920 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1921 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001922 }
1923 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001924}
1925
Chris Lattner4e998b22004-09-29 05:07:12 +00001926
1927/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1928/// node as operand #0, see if we can fold the instruction into the PHI (which
1929/// is only possible if all operands to the PHI are constants).
1930Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1931 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001932 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001933 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001934
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001935 // Check to see if all of the operands of the PHI are constants. If there is
1936 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001937 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001938 BasicBlock *NonConstBB = 0;
1939 for (unsigned i = 0; i != NumPHIValues; ++i)
1940 if (!isa<Constant>(PN->getIncomingValue(i))) {
1941 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001942 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001943 NonConstBB = PN->getIncomingBlock(i);
1944
1945 // If the incoming non-constant value is in I's block, we have an infinite
1946 // loop.
1947 if (NonConstBB == I.getParent())
1948 return 0;
1949 }
1950
1951 // If there is exactly one non-constant value, we can insert a copy of the
1952 // operation in that block. However, if this is a critical edge, we would be
1953 // inserting the computation one some other paths (e.g. inside a loop). Only
1954 // do this if the pred block is unconditionally branching into the phi block.
1955 if (NonConstBB) {
1956 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1957 if (!BI || !BI->isUnconditional()) return 0;
1958 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001959
1960 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001961 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001962 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001963 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001964 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001965
1966 // Next, add all of the operands to the PHI.
1967 if (I.getNumOperands() == 2) {
1968 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001969 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001970 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001971 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001972 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001973 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001974 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001975 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001976 } else {
1977 assert(PN->getIncomingBlock(i) == NonConstBB);
1978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001979 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001980 PN->getIncomingValue(i), C, "phitmp",
1981 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001982 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001983 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001984 CI->getPredicate(),
1985 PN->getIncomingValue(i), C, "phitmp",
1986 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001987 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001988 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989
Chris Lattnerdbab3862007-03-02 21:28:56 +00001990 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001991 }
1992 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001993 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001994 } else {
1995 CastInst *CI = cast<CastInst>(&I);
1996 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001997 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001998 Value *InV;
1999 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002000 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 } else {
2002 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002003 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002004 I.getType(), "phitmp",
2005 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002006 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002007 }
2008 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002009 }
2010 }
2011 return ReplaceInstUsesWith(I, NewPN);
2012}
2013
Chris Lattner2454a2e2008-01-29 06:52:45 +00002014
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002015/// WillNotOverflowSignedAdd - Return true if we can prove that:
2016/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2017/// This basically requires proving that the add in the original type would not
2018/// overflow to change the sign bit or have a carry out.
2019bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2020 // There are different heuristics we can use for this. Here are some simple
2021 // ones.
2022
2023 // Add has the property that adding any two 2's complement numbers can only
2024 // have one carry bit which can change a sign. As such, if LHS and RHS each
2025 // have at least two sign bits, we know that the addition of the two values will
2026 // sign extend fine.
2027 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2028 return true;
2029
2030
2031 // If one of the operands only has one non-zero bit, and if the other operand
2032 // has a known-zero bit in a more significant place than it (not including the
2033 // sign bit) the ripple may go up to and fill the zero, but won't change the
2034 // sign. For example, (X & ~4) + 1.
2035
2036 // TODO: Implement.
2037
2038 return false;
2039}
2040
Chris Lattner2454a2e2008-01-29 06:52:45 +00002041
Chris Lattner7e708292002-06-25 16:13:24 +00002042Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002043 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002044 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002045
Chris Lattner66331a42004-04-10 22:01:55 +00002046 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002047 // X + undef -> undef
2048 if (isa<UndefValue>(RHS))
2049 return ReplaceInstUsesWith(I, RHS);
2050
Chris Lattner66331a42004-04-10 22:01:55 +00002051 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002052 if (RHSC->isNullValue())
2053 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002054
Chris Lattner66331a42004-04-10 22:01:55 +00002055 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002056 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002057 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002058 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002059 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002060 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002061
2062 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2063 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002064 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002065 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002066
Eli Friedman709b33d2009-07-13 22:27:52 +00002067 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002068 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002069 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohman186a6362009-08-12 16:04:34 +00002070 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002071 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002072
2073 if (isa<PHINode>(LHS))
2074 if (Instruction *NV = FoldOpIntoPhi(I))
2075 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002076
Chris Lattner4f637d42006-01-06 17:59:59 +00002077 ConstantInt *XorRHS = 0;
2078 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002079 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002080 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002081 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002082 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002083
Zhou Sheng4351c642007-04-02 08:20:41 +00002084 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002085 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2086 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002087 do {
2088 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002089 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2090 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002091 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2092 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002093 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002094 if (!MaskedValueIsZero(XorLHS,
2095 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002096 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002097 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002098 }
2099 }
2100 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002101 C0080Val = APIntOps::lshr(C0080Val, Size);
2102 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2103 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002104
Reid Spencer35c38852007-03-28 01:36:16 +00002105 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002106 // with funny bit widths then this switch statement should be removed. It
2107 // is just here to get the size of the "middle" type back up to something
2108 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002109 const Type *MiddleType = 0;
2110 switch (Size) {
2111 default: break;
2112 case 32: MiddleType = Type::Int32Ty; break;
2113 case 16: MiddleType = Type::Int16Ty; break;
2114 case 8: MiddleType = Type::Int8Ty; break;
2115 }
2116 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002117 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002118 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002119 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002120 }
2121 }
Chris Lattner66331a42004-04-10 22:01:55 +00002122 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002123
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002124 if (I.getType() == Type::Int1Ty)
2125 return BinaryOperator::CreateXor(LHS, RHS);
2126
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002127 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002128 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002129 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002130 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002131
2132 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2133 if (RHSI->getOpcode() == Instruction::Sub)
2134 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2135 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2136 }
2137 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2138 if (LHSI->getOpcode() == Instruction::Sub)
2139 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2140 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2141 }
Robert Bocchino71698282004-07-27 21:02:21 +00002142 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002143
Chris Lattner5c4afb92002-05-08 22:46:53 +00002144 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002145 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002146 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002147 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002148 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002149 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002150 InsertNewInstBefore(NewAdd, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00002151 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002152 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002153 }
2154
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002155 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002156 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002157
2158 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002159 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002160 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002162
Misha Brukmanfd939082005-04-21 23:48:37 +00002163
Chris Lattner50af16a2004-11-13 19:50:12 +00002164 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002165 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002166 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002167 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002168
2169 // X*C1 + X*C2 --> X * (C1+C2)
2170 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002171 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002172 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002173 }
2174
2175 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002176 if (dyn_castFoldableMul(RHS, C2) == LHS)
2177 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002178
Chris Lattnere617c9e2007-01-05 02:17:46 +00002179 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002180 if (dyn_castNotVal(LHS) == RHS ||
2181 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002182 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002183
Chris Lattnerad3448c2003-02-18 19:57:07 +00002184
Chris Lattner564a7272003-08-13 19:01:45 +00002185 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002186 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2187 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002188 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002189
2190 // A+B --> A|B iff A and B have no bits set in common.
2191 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2192 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2193 APInt LHSKnownOne(IT->getBitWidth(), 0);
2194 APInt LHSKnownZero(IT->getBitWidth(), 0);
2195 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2196 if (LHSKnownZero != 0) {
2197 APInt RHSKnownOne(IT->getBitWidth(), 0);
2198 APInt RHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2200
2201 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002202 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002203 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002204 }
2205 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002206
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002207 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002208 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002209 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002210 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2211 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002212 if (W != Y) {
2213 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002214 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002215 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002216 std::swap(W, X);
2217 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002218 std::swap(Y, Z);
2219 std::swap(W, X);
2220 }
2221 }
2222
2223 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002224 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002225 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002226 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002227 }
2228 }
2229 }
2230
Chris Lattner6b032052003-10-02 15:11:26 +00002231 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002232 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002233 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002234 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002235
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002236 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002237 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002238 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002239 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002240 if (Anded == CRHS) {
2241 // See if all bits from the first bit set in the Add RHS up are included
2242 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002243 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002244
2245 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002246 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002247
2248 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002249 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002250
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002251 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2252 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002253 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002255 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002256 }
2257 }
2258 }
2259
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002260 // Try to fold constant add into select arguments.
2261 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002262 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002263 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002264 }
2265
Chris Lattner42790482007-12-20 01:56:58 +00002266 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002267 {
2268 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002269 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002270 if (!SI) {
2271 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002272 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002273 }
Chris Lattner42790482007-12-20 01:56:58 +00002274 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002275 Value *TV = SI->getTrueValue();
2276 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002277 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002278
2279 // Can we fold the add into the argument of the select?
2280 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002281 if (match(FV, m_Zero()) &&
2282 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002283 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002284 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002285 if (match(TV, m_Zero()) &&
2286 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002288 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002289 }
2290 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002291
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002292 // Check for (add (sext x), y), see if we can merge this into an
2293 // integer add followed by a sext.
2294 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2295 // (add (sext x), cst) --> (sext (add x, cst'))
2296 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2297 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002298 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002299 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002300 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002301 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2302 // Insert the new, smaller add.
2303 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2304 CI, "addconv");
2305 InsertNewInstBefore(NewAdd, I);
2306 return new SExtInst(NewAdd, I.getType());
2307 }
2308 }
2309
2310 // (add (sext x), (sext y)) --> (sext (add int x, y))
2311 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2312 // Only do this if x/y have the same type, if at last one of them has a
2313 // single use (so we don't increase the number of sexts), and if the
2314 // integer add will not overflow.
2315 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2316 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2317 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2318 RHSConv->getOperand(0))) {
2319 // Insert the new integer add.
2320 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2321 RHSConv->getOperand(0),
2322 "addconv");
2323 InsertNewInstBefore(NewAdd, I);
2324 return new SExtInst(NewAdd, I.getType());
2325 }
2326 }
2327 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002328
2329 return Changed ? &I : 0;
2330}
2331
2332Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2333 bool Changed = SimplifyCommutative(I);
2334 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2335
2336 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2337 // X + 0 --> X
2338 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002339 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002340 (I.getType())->getValueAPF()))
2341 return ReplaceInstUsesWith(I, LHS);
2342 }
2343
2344 if (isa<PHINode>(LHS))
2345 if (Instruction *NV = FoldOpIntoPhi(I))
2346 return NV;
2347 }
2348
2349 // -A + B --> B - A
2350 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002351 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002352 return BinaryOperator::CreateFSub(RHS, LHSV);
2353
2354 // A + -B --> A - B
2355 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002356 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002357 return BinaryOperator::CreateFSub(LHS, V);
2358
2359 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2360 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2361 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2362 return ReplaceInstUsesWith(I, LHS);
2363
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002364 // Check for (add double (sitofp x), y), see if we can merge this into an
2365 // integer add followed by a promotion.
2366 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2367 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2368 // ... if the constant fits in the integer value. This is useful for things
2369 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2370 // requires a constant pool load, and generally allows the add to be better
2371 // instcombined.
2372 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2373 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002374 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002375 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002376 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002377 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2378 // Insert the new integer add.
2379 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2380 CI, "addconv");
2381 InsertNewInstBefore(NewAdd, I);
2382 return new SIToFPInst(NewAdd, I.getType());
2383 }
2384 }
2385
2386 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2387 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2388 // Only do this if x/y have the same type, if at last one of them has a
2389 // single use (so we don't increase the number of int->fp conversions),
2390 // and if the integer add will not overflow.
2391 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2392 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2393 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2394 RHSConv->getOperand(0))) {
2395 // Insert the new integer add.
2396 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2397 RHSConv->getOperand(0),
2398 "addconv");
2399 InsertNewInstBefore(NewAdd, I);
2400 return new SIToFPInst(NewAdd, I.getType());
2401 }
2402 }
2403 }
2404
Chris Lattner7e708292002-06-25 16:13:24 +00002405 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002406}
2407
Chris Lattner7e708292002-06-25 16:13:24 +00002408Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002410
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002411 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002413
Chris Lattner233f7dc2002-08-12 21:17:25 +00002414 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002415 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002416 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002417
Chris Lattnere87597f2004-10-16 18:11:37 +00002418 if (isa<UndefValue>(Op0))
2419 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2420 if (isa<UndefValue>(Op1))
2421 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2422
Chris Lattnerd65460f2003-11-05 01:06:05 +00002423 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002425 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002426 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002427
Chris Lattnerd65460f2003-11-05 01:06:05 +00002428 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002429 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002430 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002431 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002432
Chris Lattner76b7a062007-01-15 07:02:54 +00002433 // -(X >>u 31) -> (X >>s 31)
2434 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002435 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002436 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002437 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002438 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002439 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002440 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002441 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002442 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002444 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002445 }
2446 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002447 }
2448 else if (SI->getOpcode() == Instruction::AShr) {
2449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002451 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002453 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002455 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002456 }
2457 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002458 }
2459 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002460 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002461
2462 // Try to fold constant sub into select arguments.
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002465 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002466
2467 // C - zext(bool) -> bool ? C - 1 : C
2468 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2469 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohman186a6362009-08-12 16:04:34 +00002470 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002471 }
2472
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002473 if (I.getType() == Type::Int1Ty)
2474 return BinaryOperator::CreateXor(Op0, Op1);
2475
Chris Lattner43d84d62005-04-07 16:15:25 +00002476 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002477 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002478 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002479 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002480 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002481 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002482 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002483 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002487 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002488 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002489 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002490 }
2491
Chris Lattnerfd059242003-10-15 16:48:29 +00002492 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2495 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002496 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // Swap the two operands of the subexpr...
2498 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499 Op1I->setOperand(0, IIOp1);
2500 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002501
Chris Lattnera2881962003-02-18 19:28:33 +00002502 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002504 }
2505
2506 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2507 //
2508 if (Op1I->getOpcode() == Instruction::And &&
2509 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2511
Chris Lattnerf523d062004-06-09 05:08:07 +00002512 Value *NewNot =
Dan Gohman4ae51262009-08-12 16:23:25 +00002513 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002515 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002516
Reid Spencerac5209e2006-10-16 23:08:08 +00002517 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002518 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002519 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002520 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002521 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002523 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002524
Chris Lattnerad3448c2003-02-18 19:57:07 +00002525 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002526 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002527 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002528 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002529 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002530 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002531 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002532 }
Chris Lattner40371712002-05-09 01:29:19 +00002533 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002534 }
Chris Lattnera2881962003-02-18 19:28:33 +00002535
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002536 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2537 if (Op0I->getOpcode() == Instruction::Add) {
2538 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2539 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2540 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2541 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2542 } else if (Op0I->getOpcode() == Instruction::Sub) {
2543 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002544 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002545 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002546 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002547 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002548
Chris Lattner50af16a2004-11-13 19:50:12 +00002549 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002550 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002551 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002552 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002553
Chris Lattner50af16a2004-11-13 19:50:12 +00002554 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002555 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002556 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002557 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002558 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002559}
2560
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002561Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2563
2564 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002565 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002566 return BinaryOperator::CreateFAdd(Op0, V);
2567
2568 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2569 if (Op1I->getOpcode() == Instruction::FAdd) {
2570 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002571 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002572 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002573 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002574 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002575 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002577 }
2578
2579 return 0;
2580}
2581
Chris Lattnera0141b92007-07-15 20:42:37 +00002582/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2583/// comparison only checks the sign bit. If it only checks the sign bit, set
2584/// TrueIfSigned if the result of the comparison is true when the input value is
2585/// signed.
2586static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2587 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002588 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002589 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2590 TrueIfSigned = true;
2591 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002592 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2593 TrueIfSigned = true;
2594 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002595 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2596 TrueIfSigned = false;
2597 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002598 case ICmpInst::ICMP_UGT:
2599 // True if LHS u> RHS and RHS == high-bit-mask - 1
2600 TrueIfSigned = true;
2601 return RHS->getValue() ==
2602 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2603 case ICmpInst::ICMP_UGE:
2604 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2605 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002606 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002607 default:
2608 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002609 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002610}
2611
Chris Lattner7e708292002-06-25 16:13:24 +00002612Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002613 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002614 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002615
Eli Friedman1694e092009-07-18 09:12:15 +00002616 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002617 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002618
Chris Lattner233f7dc2002-08-12 21:17:25 +00002619 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002620 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2621 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002622
2623 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002624 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002625 if (SI->getOpcode() == Instruction::Shl)
2626 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002627 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002628 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002629
Zhou Sheng843f07672007-04-19 05:39:12 +00002630 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002631 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2632 if (CI->equalsInt(1)) // X * 1 == X
2633 return ReplaceInstUsesWith(I, Op0);
2634 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002635 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002636
Zhou Sheng97b52c22007-03-29 01:57:21 +00002637 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002638 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002639 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002640 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002641 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002642 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002643 if (Op1->isNullValue())
2644 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002645
2646 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2647 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002648 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002649
2650 // As above, vector X*splat(1.0) -> X in all defined cases.
2651 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002652 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2653 if (CI->equalsInt(1))
2654 return ReplaceInstUsesWith(I, Op0);
2655 }
2656 }
Chris Lattnera2881962003-02-18 19:28:33 +00002657 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002658
2659 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2660 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002661 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002662 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002663 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002664 Op1, "tmp");
2665 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002666 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002667 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002669
2670 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002671
2672 // Try to fold constant mul into select arguments.
2673 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002674 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002675 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002676
2677 if (isa<PHINode>(Op0))
2678 if (Instruction *NV = FoldOpIntoPhi(I))
2679 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002680 }
2681
Dan Gohman186a6362009-08-12 16:04:34 +00002682 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2683 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002685
Nick Lewycky0c730792008-11-21 07:33:58 +00002686 // (X / Y) * Y = X - (X % Y)
2687 // (X / Y) * -Y = (X % Y) - X
2688 {
2689 Value *Op1 = I.getOperand(1);
2690 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2691 if (!BO ||
2692 (BO->getOpcode() != Instruction::UDiv &&
2693 BO->getOpcode() != Instruction::SDiv)) {
2694 Op1 = Op0;
2695 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2696 }
Dan Gohman186a6362009-08-12 16:04:34 +00002697 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002698 if (BO && BO->hasOneUse() &&
2699 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700 (BO->getOpcode() == Instruction::UDiv ||
2701 BO->getOpcode() == Instruction::SDiv)) {
2702 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2703
2704 Instruction *Rem;
2705 if (BO->getOpcode() == Instruction::UDiv)
2706 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2707 else
2708 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2709
2710 InsertNewInstBefore(Rem, I);
2711 Rem->takeName(BO);
2712
2713 if (Op1BO == Op1)
2714 return BinaryOperator::CreateSub(Op0BO, Rem);
2715 else
2716 return BinaryOperator::CreateSub(Rem, Op0BO);
2717 }
2718 }
2719
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002720 if (I.getType() == Type::Int1Ty)
2721 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2722
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002723 // If one of the operands of the multiply is a cast from a boolean value, then
2724 // we know the bool is either zero or one, so this is a 'masking' multiply.
2725 // See if we can simplify things based on how the boolean was originally
2726 // formed.
2727 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002728 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002729 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002730 BoolCast = CI;
2731 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002732 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002733 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002734 BoolCast = CI;
2735 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002736 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002737 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2738 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002739 bool TIS = false;
2740
Reid Spencere4d87aa2006-12-23 06:05:41 +00002741 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002742 // multiply into a shift/and combination.
2743 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002744 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2745 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002746 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002747 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002748 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002749 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002750 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002751 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002752 BoolCast->getOperand(0)->getName()+
2753 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002754
2755 // If the multiply type is not the same as the source type, sign extend
2756 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002757 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002758 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2759 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002760 Instruction::CastOps opcode =
2761 (SrcBits == DstBits ? Instruction::BitCast :
2762 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2763 V = InsertCastBefore(opcode, V, I.getType(), I);
2764 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002765
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002766 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002768 }
2769 }
2770 }
2771
Chris Lattner7e708292002-06-25 16:13:24 +00002772 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002773}
2774
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002775Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2776 bool Changed = SimplifyCommutative(I);
2777 Value *Op0 = I.getOperand(0);
2778
2779 // Simplify mul instructions with a constant RHS...
2780 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2781 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2782 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2783 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2784 if (Op1F->isExactlyValue(1.0))
2785 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2786 } else if (isa<VectorType>(Op1->getType())) {
2787 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2788 // As above, vector X*splat(1.0) -> X in all defined cases.
2789 if (Constant *Splat = Op1V->getSplatValue()) {
2790 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2791 if (F->isExactlyValue(1.0))
2792 return ReplaceInstUsesWith(I, Op0);
2793 }
2794 }
2795 }
2796
2797 // Try to fold constant mul into select arguments.
2798 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2799 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2800 return R;
2801
2802 if (isa<PHINode>(Op0))
2803 if (Instruction *NV = FoldOpIntoPhi(I))
2804 return NV;
2805 }
2806
Dan Gohman186a6362009-08-12 16:04:34 +00002807 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2808 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002809 return BinaryOperator::CreateFMul(Op0v, Op1v);
2810
2811 return Changed ? &I : 0;
2812}
2813
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002814/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2815/// instruction.
2816bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2817 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2818
2819 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2820 int NonNullOperand = -1;
2821 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2822 if (ST->isNullValue())
2823 NonNullOperand = 2;
2824 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2825 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2826 if (ST->isNullValue())
2827 NonNullOperand = 1;
2828
2829 if (NonNullOperand == -1)
2830 return false;
2831
2832 Value *SelectCond = SI->getOperand(0);
2833
2834 // Change the div/rem to use 'Y' instead of the select.
2835 I.setOperand(1, SI->getOperand(NonNullOperand));
2836
2837 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2838 // problem. However, the select, or the condition of the select may have
2839 // multiple uses. Based on our knowledge that the operand must be non-zero,
2840 // propagate the known value for the select into other uses of it, and
2841 // propagate a known value of the condition into its other users.
2842
2843 // If the select and condition only have a single use, don't bother with this,
2844 // early exit.
2845 if (SI->use_empty() && SelectCond->hasOneUse())
2846 return true;
2847
2848 // Scan the current block backward, looking for other uses of SI.
2849 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2850
2851 while (BBI != BBFront) {
2852 --BBI;
2853 // If we found a call to a function, we can't assume it will return, so
2854 // information from below it cannot be propagated above it.
2855 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2856 break;
2857
2858 // Replace uses of the select or its condition with the known values.
2859 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2860 I != E; ++I) {
2861 if (*I == SI) {
2862 *I = SI->getOperand(NonNullOperand);
2863 AddToWorkList(BBI);
2864 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002865 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2866 ConstantInt::getFalse(*Context);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002867 AddToWorkList(BBI);
2868 }
2869 }
2870
2871 // If we past the instruction, quit looking for it.
2872 if (&*BBI == SI)
2873 SI = 0;
2874 if (&*BBI == SelectCond)
2875 SelectCond = 0;
2876
2877 // If we ran out of things to eliminate, break out of the loop.
2878 if (SelectCond == 0 && SI == 0)
2879 break;
2880
2881 }
2882 return true;
2883}
2884
2885
Reid Spencer1628cec2006-10-26 06:15:43 +00002886/// This function implements the transforms on div instructions that work
2887/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2888/// used by the visitors to those instructions.
2889/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002890Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002892
Chris Lattner50b2ca42008-02-19 06:12:18 +00002893 // undef / X -> 0 for integer.
2894 // undef / X -> undef for FP (the undef could be a snan).
2895 if (isa<UndefValue>(Op0)) {
2896 if (Op0->getType()->isFPOrFPVector())
2897 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002898 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002899 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002900
2901 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002902 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002903 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002904
Reid Spencer1628cec2006-10-26 06:15:43 +00002905 return 0;
2906}
Misha Brukmanfd939082005-04-21 23:48:37 +00002907
Reid Spencer1628cec2006-10-26 06:15:43 +00002908/// This function implements the transforms common to both integer division
2909/// instructions (udiv and sdiv). It is called by the visitors to those integer
2910/// division instructions.
2911/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002912Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002915 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002916 if (Op0 == Op1) {
2917 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002918 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002919 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002920 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002921 }
2922
Owen Andersoneed707b2009-07-24 23:12:02 +00002923 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002924 return ReplaceInstUsesWith(I, CI);
2925 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002926
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 if (Instruction *Common = commonDivTransforms(I))
2928 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002929
2930 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2931 // This does not apply for fdiv.
2932 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2933 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002934
2935 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2936 // div X, 1 == X
2937 if (RHS->equalsInt(1))
2938 return ReplaceInstUsesWith(I, Op0);
2939
2940 // (X / C1) / C2 -> X / (C1*C2)
2941 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2942 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2943 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002944 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002945 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002947 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002948 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002949 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002950 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002951
Reid Spencerbca0e382007-03-23 20:05:17 +00002952 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002953 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2954 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2955 return R;
2956 if (isa<PHINode>(Op0))
2957 if (Instruction *NV = FoldOpIntoPhi(I))
2958 return NV;
2959 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002960 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002961
Chris Lattnera2881962003-02-18 19:28:33 +00002962 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002963 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002964 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002966
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002967 // It can't be division by zero, hence it must be division by one.
2968 if (I.getType() == Type::Int1Ty)
2969 return ReplaceInstUsesWith(I, Op0);
2970
Nick Lewycky895f0852008-11-27 20:21:08 +00002971 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2972 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2973 // div X, 1 == X
2974 if (X->isOne())
2975 return ReplaceInstUsesWith(I, Op0);
2976 }
2977
Reid Spencer1628cec2006-10-26 06:15:43 +00002978 return 0;
2979}
2980
2981Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2983
2984 // Handle the integer div common cases
2985 if (Instruction *Common = commonIDivTransforms(I))
2986 return Common;
2987
Reid Spencer1628cec2006-10-26 06:15:43 +00002988 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002989 // X udiv C^2 -> X >> C
2990 // Check to see if this is an unsigned division with an exact power of 2,
2991 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002992 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002993 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002994 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002995
2996 // X udiv C, where C >= signbit
2997 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00002998 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
2999 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003000 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003001 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003002 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003003 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003004 }
3005
3006 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003007 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003008 if (RHSI->getOpcode() == Instruction::Shl &&
3009 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003010 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003011 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003012 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003013 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003014 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003015 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003016 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003017 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003018 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003019 }
3020 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003021 }
3022
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3024 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003025 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003027 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003028 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003029 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003030 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003031 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003032 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003033 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003035 Op0, TC, SI->getName()+".t");
3036 TSI = InsertNewInstBefore(TSI, I);
3037
3038 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003039 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 Op0, FC, SI->getName()+".f");
3042 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003043
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003044 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003045 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003046 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003047 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003048 return 0;
3049}
3050
Reid Spencer1628cec2006-10-26 06:15:43 +00003051Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
3054 // Handle the integer div common cases
3055 if (Instruction *Common = commonIDivTransforms(I))
3056 return Common;
3057
3058 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3059 // sdiv X, -1 == -X
3060 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003061 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003062
3063 // sdiv X, C --> ashr X, log2(C)
3064 if (cast<SDivOperator>(&I)->isExact() &&
3065 RHS->getValue().isNonNegative() &&
3066 RHS->getValue().isPowerOf2()) {
3067 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3068 RHS->getValue().exactLogBase2());
3069 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3070 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003071 }
3072
3073 // If the sign bits of both operands are zero (i.e. we can prove they are
3074 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003075 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003076 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003077 if (MaskedValueIsZero(Op0, Mask)) {
3078 if (MaskedValueIsZero(Op1, Mask)) {
3079 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3080 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3081 }
3082 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003083 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003084 ShiftedInt->getValue().isPowerOf2()) {
3085 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3086 // Safe because the only negative value (1 << Y) can take on is
3087 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3088 // the sign bit set.
3089 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3090 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003091 }
Eli Friedman8be17392009-07-18 09:53:21 +00003092 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003093
3094 return 0;
3095}
3096
3097Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3098 return commonDivTransforms(I);
3099}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003100
Reid Spencer0a783f72006-11-02 01:53:59 +00003101/// This function implements the transforms on rem instructions that work
3102/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3103/// is used by the visitors to those instructions.
3104/// @brief Transforms common to all three rem instructions
3105Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003106 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003107
Chris Lattner50b2ca42008-02-19 06:12:18 +00003108 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3109 if (I.getType()->isFPOrFPVector())
3110 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003111 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003112 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003113 if (isa<UndefValue>(Op1))
3114 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003115
3116 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003117 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3118 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003119
Reid Spencer0a783f72006-11-02 01:53:59 +00003120 return 0;
3121}
3122
3123/// This function implements the transforms common to both integer remainder
3124/// instructions (urem and srem). It is called by the visitors to those integer
3125/// remainder instructions.
3126/// @brief Common integer remainder transforms
3127Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3129
3130 if (Instruction *common = commonRemTransforms(I))
3131 return common;
3132
Dale Johannesened6af242009-01-21 00:35:19 +00003133 // 0 % X == 0 for integer, we don't need to preserve faults!
3134 if (Constant *LHS = dyn_cast<Constant>(Op0))
3135 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003136 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003137
Chris Lattner857e8cd2004-12-12 21:48:58 +00003138 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003139 // X % 0 == undef, we don't need to preserve faults!
3140 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003141 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003142
Chris Lattnera2881962003-02-18 19:28:33 +00003143 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003144 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003145
Chris Lattner97943922006-02-28 05:49:21 +00003146 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3149 return R;
3150 } else if (isa<PHINode>(Op0I)) {
3151 if (Instruction *NV = FoldOpIntoPhi(I))
3152 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003153 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003154
3155 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003156 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003157 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003158 }
Chris Lattnera2881962003-02-18 19:28:33 +00003159 }
3160
Reid Spencer0a783f72006-11-02 01:53:59 +00003161 return 0;
3162}
3163
3164Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
3167 if (Instruction *common = commonIRemTransforms(I))
3168 return common;
3169
3170 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3171 // X urem C^2 -> X and C
3172 // Check to see if this is an unsigned remainder with an exact power of 2,
3173 // if so, convert to a bitwise and.
3174 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003175 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003176 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003177 }
3178
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003179 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003180 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3181 if (RHSI->getOpcode() == Instruction::Shl &&
3182 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003183 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003184 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003185 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003186 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003187 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003188 }
3189 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003191
Reid Spencer0a783f72006-11-02 01:53:59 +00003192 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3193 // where C1&C2 are powers of two.
3194 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3195 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3196 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3197 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003198 if ((STO->getValue().isPowerOf2()) &&
3199 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003200 Value *TrueAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003201 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003202 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 Value *FalseAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003204 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003205 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003206 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003207 }
3208 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003209 }
3210
Chris Lattner3f5b8772002-05-06 16:14:14 +00003211 return 0;
3212}
3213
Reid Spencer0a783f72006-11-02 01:53:59 +00003214Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3215 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3216
Dan Gohmancff55092007-11-05 23:16:33 +00003217 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 if (Instruction *common = commonIRemTransforms(I))
3219 return common;
3220
Dan Gohman186a6362009-08-12 16:04:34 +00003221 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003222 if (!isa<Constant>(RHSNeg) ||
3223 (isa<ConstantInt>(RHSNeg) &&
3224 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003225 // X % -Y -> X % Y
3226 AddUsesToWorkList(I);
3227 I.setOperand(1, RHSNeg);
3228 return &I;
3229 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003230
Dan Gohmancff55092007-11-05 23:16:33 +00003231 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003232 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003233 if (I.getType()->isInteger()) {
3234 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3235 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3236 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003237 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003238 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 }
3240
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003241 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003242 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3243 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003244
Nick Lewycky9dce8732008-12-20 16:48:00 +00003245 bool hasNegative = false;
3246 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3247 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3248 if (RHS->getValue().isNegative())
3249 hasNegative = true;
3250
3251 if (hasNegative) {
3252 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003253 for (unsigned i = 0; i != VWidth; ++i) {
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3255 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003256 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003257 else
3258 Elts[i] = RHS;
3259 }
3260 }
3261
Owen Andersonaf7ec972009-07-28 21:19:26 +00003262 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003263 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003264 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003265 I.setOperand(1, NewRHSV);
3266 return &I;
3267 }
3268 }
3269 }
3270
Reid Spencer0a783f72006-11-02 01:53:59 +00003271 return 0;
3272}
3273
3274Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003275 return commonRemTransforms(I);
3276}
3277
Chris Lattner457dd822004-06-09 07:59:58 +00003278// isOneBitSet - Return true if there is exactly one bit set in the specified
3279// constant.
3280static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003281 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003282}
3283
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003284// isHighOnes - Return true if the constant is of the form 1+0+.
3285// This is the same as lowones(~X).
3286static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003287 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003288}
3289
Reid Spencere4d87aa2006-12-23 06:05:41 +00003290/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003291/// are carefully arranged to allow folding of expressions such as:
3292///
3293/// (A < B) | (A > B) --> (A != B)
3294///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003295/// Note that this is only valid if the first and second predicates have the
3296/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003297///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298/// Three bits are used to represent the condition, as follows:
3299/// 0 A > B
3300/// 1 A == B
3301/// 2 A < B
3302///
3303/// <=> Value Definition
3304/// 000 0 Always false
3305/// 001 1 A > B
3306/// 010 2 A == B
3307/// 011 3 A >= B
3308/// 100 4 A < B
3309/// 101 5 A != B
3310/// 110 6 A <= B
3311/// 111 7 Always true
3312///
3313static unsigned getICmpCode(const ICmpInst *ICI) {
3314 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003315 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003316 case ICmpInst::ICMP_UGT: return 1; // 001
3317 case ICmpInst::ICMP_SGT: return 1; // 001
3318 case ICmpInst::ICMP_EQ: return 2; // 010
3319 case ICmpInst::ICMP_UGE: return 3; // 011
3320 case ICmpInst::ICMP_SGE: return 3; // 011
3321 case ICmpInst::ICMP_ULT: return 4; // 100
3322 case ICmpInst::ICMP_SLT: return 4; // 100
3323 case ICmpInst::ICMP_NE: return 5; // 101
3324 case ICmpInst::ICMP_ULE: return 6; // 110
3325 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003326 // True -> 7
3327 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003328 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003329 return 0;
3330 }
3331}
3332
Evan Cheng8db90722008-10-14 17:15:11 +00003333/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3334/// predicate into a three bit mask. It also returns whether it is an ordered
3335/// predicate by reference.
3336static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3337 isOrdered = false;
3338 switch (CC) {
3339 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3340 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003341 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3342 case FCmpInst::FCMP_UGT: return 1; // 001
3343 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3344 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003345 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3346 case FCmpInst::FCMP_UGE: return 3; // 011
3347 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3348 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003349 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3350 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003351 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3352 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003353 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003354 default:
3355 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003356 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003357 return 0;
3358 }
3359}
3360
Reid Spencere4d87aa2006-12-23 06:05:41 +00003361/// getICmpValue - This is the complement of getICmpCode, which turns an
3362/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003363/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003364/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003365static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003366 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003368 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003369 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 case 1:
3371 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003372 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373 else
Owen Anderson333c4002009-07-09 23:48:35 +00003374 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3375 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376 case 3:
3377 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003378 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 else
Owen Anderson333c4002009-07-09 23:48:35 +00003380 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 case 4:
3382 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 else
Owen Anderson333c4002009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3386 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 case 6:
3388 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003389 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 else
Owen Anderson333c4002009-07-09 23:48:35 +00003391 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003392 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003393 }
3394}
3395
Evan Cheng8db90722008-10-14 17:15:11 +00003396/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3397/// opcode and two operands into either a FCmp instruction. isordered is passed
3398/// in to determine which kind of predicate to use in the new fcmp instruction.
3399static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003400 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003401 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003402 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003403 case 0:
3404 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003405 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003406 else
Owen Anderson333c4002009-07-09 23:48:35 +00003407 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003408 case 1:
3409 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003413 case 2:
3414 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003416 else
Owen Anderson333c4002009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003418 case 3:
3419 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, 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_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003423 case 4:
3424 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003426 else
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 case 5:
3429 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003431 else
Owen Anderson333c4002009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003433 case 6:
3434 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, 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_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003438 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003439 }
3440}
3441
Chris Lattnerb9553d62008-11-16 04:55:20 +00003442/// PredicatesFoldable - Return true if both predicates match sign or if at
3443/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003444static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3445 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003446 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3447 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003448}
3449
3450namespace {
3451// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3452struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003453 InstCombiner &IC;
3454 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003455 ICmpInst::Predicate pred;
3456 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3457 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3458 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003459 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3461 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003462 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3463 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003464 return false;
3465 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 Instruction *apply(Instruction &Log) const {
3467 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3468 if (ICI->getOperand(0) != LHS) {
3469 assert(ICI->getOperand(1) == LHS);
3470 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003471 }
3472
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003473 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003475 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 unsigned Code;
3477 switch (Log.getOpcode()) {
3478 case Instruction::And: Code = LHSCode & RHSCode; break;
3479 case Instruction::Or: Code = LHSCode | RHSCode; break;
3480 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003481 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003482 }
3483
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003484 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3485 ICmpInst::isSignedPredicate(ICI->getPredicate());
3486
Owen Andersond672ecb2009-07-03 00:17:18 +00003487 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 if (Instruction *I = dyn_cast<Instruction>(RV))
3489 return I;
3490 // Otherwise, it's a constant boolean value...
3491 return IC.ReplaceInstUsesWith(Log, RV);
3492 }
3493};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003494} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003496// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3497// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003498// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003499Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003500 ConstantInt *OpRHS,
3501 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003502 BinaryOperator &TheAnd) {
3503 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003504 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003505 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003506 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003507
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003508 switch (Op->getOpcode()) {
3509 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003510 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003511 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003512 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003514 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 }
3517 break;
3518 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003519 if (Together == AndRHS) // (X | C) & C --> C
3520 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003521
Chris Lattner6e7ba452005-01-01 16:22:27 +00003522 if (Op->hasOneUse() && Together != OpRHS) {
3523 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003524 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003525 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003526 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003527 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528 }
3529 break;
3530 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003531 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 // Adding a one to a single bit bit-field should be turned into an XOR
3533 // of the bit. First thing to check is to see if this AND is with a
3534 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003535 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003536
3537 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003538 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539 // Ok, at this point, we know that we are masking the result of the
3540 // ADD down to exactly one bit. If the constant we are adding has
3541 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003542 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003543
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Check to see if any bits below the one bit set in AndRHSV are set.
3545 if ((AddRHS & (AndRHSV-1)) == 0) {
3546 // If not, the only thing that can effect the output of the AND is
3547 // the bit specified by AndRHSV. If that bit is set, the effect of
3548 // the XOR is to toggle the bit. If it is clear, then the ADD has
3549 // no effect.
3550 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3551 TheAnd.setOperand(0, X);
3552 return &TheAnd;
3553 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003554 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003555 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003556 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003557 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003558 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 }
3560 }
3561 }
3562 }
3563 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003564
3565 case Instruction::Shl: {
3566 // We know that the AND will not produce any of the bits shifted in, so if
3567 // the anded constant includes them, clear them now!
3568 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003569 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003570 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003571 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003572 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003573
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 if (CI->getValue() == ShlMask) {
3575 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003576 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3577 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003578 TheAnd.setOperand(1, CI);
3579 return &TheAnd;
3580 }
3581 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003582 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003583 case Instruction::LShr:
3584 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003585 // We know that the AND will not produce any of the bits shifted in, so if
3586 // the anded constant includes them, clear them now! This only applies to
3587 // unsigned shifts, because a signed shr may bring in set bits!
3588 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003589 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003590 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003591 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003592 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003593
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 if (CI->getValue() == ShrMask) {
3595 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003596 return ReplaceInstUsesWith(TheAnd, Op);
3597 } else if (CI != AndRHS) {
3598 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3599 return &TheAnd;
3600 }
3601 break;
3602 }
3603 case Instruction::AShr:
3604 // Signed shr.
3605 // See if this is shifting in some sign extension, then masking it out
3606 // with an and.
3607 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003608 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003609 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003610 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003611 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003612 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003613 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003614 // Make the argument unsigned.
3615 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003616 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003617 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003618 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003619 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003620 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003621 }
3622 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003623 }
3624 return 0;
3625}
3626
Chris Lattner8b170942002-08-09 23:47:40 +00003627
Chris Lattnera96879a2004-09-29 17:40:11 +00003628/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3629/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003630/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3631/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003632/// insert new instructions.
3633Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634 bool isSigned, bool Inside,
3635 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003636 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003637 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003638 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639
Chris Lattnera96879a2004-09-29 17:40:11 +00003640 if (Inside) {
3641 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003642 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003643
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003645 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003646 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003648 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 }
3650
3651 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003652 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003653 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003654 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003655 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003656 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003657 }
3658
3659 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003660 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003661
Reid Spencere4e40032007-03-21 23:19:50 +00003662 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003663 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003664 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003665 ICmpInst::Predicate pred = (isSigned ?
3666 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003667 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003669
Reid Spencere4e40032007-03-21 23:19:50 +00003670 // Emit V-Lo >u Hi-1-Lo
3671 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003672 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003673 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003674 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003675 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003676 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003677}
3678
Chris Lattner7203e152005-09-18 07:22:02 +00003679// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3680// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3681// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3682// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003683static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003684 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003685 uint32_t BitWidth = Val->getType()->getBitWidth();
3686 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003687
3688 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003689 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003690 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003691 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003692 return true;
3693}
3694
Chris Lattner7203e152005-09-18 07:22:02 +00003695/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3696/// where isSub determines whether the operator is a sub. If we can fold one of
3697/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003698///
3699/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3700/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3702///
3703/// return (A +/- B).
3704///
3705Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003706 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003707 Instruction &I) {
3708 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3709 if (!LHSI || LHSI->getNumOperands() != 2 ||
3710 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3711
3712 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3713
3714 switch (LHSI->getOpcode()) {
3715 default: return 0;
3716 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003717 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003718 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003719 if ((Mask->getValue().countLeadingZeros() +
3720 Mask->getValue().countPopulation()) ==
3721 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003722 break;
3723
3724 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3725 // part, we don't need any explicit masks to take them out of A. If that
3726 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003727 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003728 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003729 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003730 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003731 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003732 break;
3733 }
3734 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003735 return 0;
3736 case Instruction::Or:
3737 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003738 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003739 if ((Mask->getValue().countLeadingZeros() +
3740 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003741 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 break;
3743 return 0;
3744 }
3745
3746 Instruction *New;
3747 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003748 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003749 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003750 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003751 return InsertNewInstBefore(New, I);
3752}
3753
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003754/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3755Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3756 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003757 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003758 ConstantInt *LHSCst, *RHSCst;
3759 ICmpInst::Predicate LHSCC, RHSCC;
3760
Chris Lattnerea065fb2008-11-16 05:10:52 +00003761 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003762 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003763 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003764 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003765 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003766 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003767
3768 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3769 // where C is a power of 2
3770 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3771 LHSCst->getValue().isPowerOf2()) {
3772 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3773 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003774 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003775 }
3776
3777 // From here on, we only handle:
3778 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3779 if (Val != Val2) return 0;
3780
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003781 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3782 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3783 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3784 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3785 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3786 return 0;
3787
3788 // We can't fold (ugt x, C) & (sgt x, C2).
3789 if (!PredicatesFoldable(LHSCC, RHSCC))
3790 return 0;
3791
3792 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003793 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003794 if (ICmpInst::isSignedPredicate(LHSCC) ||
3795 (ICmpInst::isEquality(LHSCC) &&
3796 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003797 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003798 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003799 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3800
3801 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003802 std::swap(LHS, RHS);
3803 std::swap(LHSCst, RHSCst);
3804 std::swap(LHSCC, RHSCC);
3805 }
3806
3807 // At this point, we know we have have two icmp instructions
3808 // comparing a value against two constants and and'ing the result
3809 // together. Because of the above check, we know that we only have
3810 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3811 // (from the FoldICmpLogical check above), that the two constants
3812 // are not equal and that the larger constant is on the RHS
3813 assert(LHSCst != RHSCst && "Compares not folded above?");
3814
3815 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003816 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003817 case ICmpInst::ICMP_EQ:
3818 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003819 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003820 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3821 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3822 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003823 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003824 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3825 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3826 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3827 return ReplaceInstUsesWith(I, LHS);
3828 }
3829 case ICmpInst::ICMP_NE:
3830 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003831 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003833 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003834 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003835 break; // (X != 13 & X u< 15) -> no change
3836 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003837 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003838 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003839 break; // (X != 13 & X s< 15) -> no change
3840 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3841 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3842 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3843 return ReplaceInstUsesWith(I, RHS);
3844 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003845 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003846 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003847 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3848 Val->getName()+".off");
3849 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003850 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003851 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003852 }
3853 break; // (X != 13 & X != 15) -> no change
3854 }
3855 break;
3856 case ICmpInst::ICMP_ULT:
3857 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003858 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3860 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003861 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3863 break;
3864 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3865 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3866 return ReplaceInstUsesWith(I, LHS);
3867 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3868 break;
3869 }
3870 break;
3871 case ICmpInst::ICMP_SLT:
3872 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3875 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003876 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3878 break;
3879 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3880 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3881 return ReplaceInstUsesWith(I, LHS);
3882 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3883 break;
3884 }
3885 break;
3886 case ICmpInst::ICMP_UGT:
3887 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003888 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3890 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3891 return ReplaceInstUsesWith(I, RHS);
3892 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3893 break;
3894 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003895 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003896 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003898 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003899 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3902 break;
3903 }
3904 break;
3905 case ICmpInst::ICMP_SGT:
3906 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3909 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3910 return ReplaceInstUsesWith(I, RHS);
3911 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3912 break;
3913 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003914 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003915 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003917 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003918 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003919 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003920 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3921 break;
3922 }
3923 break;
3924 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925
3926 return 0;
3927}
3928
Chris Lattner42d1be02009-07-23 05:14:02 +00003929Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3930 FCmpInst *RHS) {
3931
3932 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3933 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3934 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3935 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3936 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3937 // If either of the constants are nans, then the whole thing returns
3938 // false.
3939 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003941 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3942 LHS->getOperand(0), RHS->getOperand(0));
3943 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003944
3945 // Handle vector zeros. This occurs because the canonical form of
3946 // "fcmp ord x,x" is "fcmp ord x, 0".
3947 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3948 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3949 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3950 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003951 return 0;
3952 }
3953
3954 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3955 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3956 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3957
3958
3959 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3960 // Swap RHS operands to match LHS.
3961 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3962 std::swap(Op1LHS, Op1RHS);
3963 }
3964
3965 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3966 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3967 if (Op0CC == Op1CC)
3968 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3969
3970 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003971 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003972 if (Op0CC == FCmpInst::FCMP_TRUE)
3973 return ReplaceInstUsesWith(I, RHS);
3974 if (Op1CC == FCmpInst::FCMP_TRUE)
3975 return ReplaceInstUsesWith(I, LHS);
3976
3977 bool Op0Ordered;
3978 bool Op1Ordered;
3979 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3980 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3981 if (Op1Pred == 0) {
3982 std::swap(LHS, RHS);
3983 std::swap(Op0Pred, Op1Pred);
3984 std::swap(Op0Ordered, Op1Ordered);
3985 }
3986 if (Op0Pred == 0) {
3987 // uno && ueq -> uno && (uno || eq) -> ueq
3988 // ord && olt -> ord && (ord && lt) -> olt
3989 if (Op0Ordered == Op1Ordered)
3990 return ReplaceInstUsesWith(I, RHS);
3991
3992 // uno && oeq -> uno && (ord && eq) -> false
3993 // uno && ord -> false
3994 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003996 // ord && ueq -> ord && (uno || eq) -> oeq
3997 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3998 Op0LHS, Op0RHS, Context));
3999 }
4000 }
4001
4002 return 0;
4003}
4004
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004005
Chris Lattner7e708292002-06-25 16:13:24 +00004006Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004007 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004009
Chris Lattnere87597f2004-10-16 18:11:37 +00004010 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004011 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004012
Chris Lattner6e7ba452005-01-01 16:22:27 +00004013 // and X, X = X
4014 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004015 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004016
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004017 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004018 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004019 if (SimplifyDemandedInstructionBits(I))
4020 return &I;
4021 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004022 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004023 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004024 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004025 } else if (isa<ConstantAggregateZero>(Op1)) {
4026 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004027 }
4028 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004029
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004030 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004031 const APInt& AndRHSMask = AndRHS->getValue();
4032 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004033
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004034 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004035 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004036 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004037 Value *Op0LHS = Op0I->getOperand(0);
4038 Value *Op0RHS = Op0I->getOperand(1);
4039 switch (Op0I->getOpcode()) {
4040 case Instruction::Xor:
4041 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004042 // If the mask is only needed on one incoming arm, push it up.
4043 if (Op0I->hasOneUse()) {
4044 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4045 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004046 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004047 Op0RHS->getName()+".masked");
4048 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004049 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004050 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004051 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004052 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004053 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4054 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004055 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 Op0LHS->getName()+".masked");
4057 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004058 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004059 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4060 }
4061 }
4062
Chris Lattner6e7ba452005-01-01 16:22:27 +00004063 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004064 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004065 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4066 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4067 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4068 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004070 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004071 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004072 break;
4073
4074 case Instruction::Sub:
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, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004080
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004081 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4082 // has 1's for all bits that the subtraction with A might affect.
4083 if (Op0I->hasOneUse()) {
4084 uint32_t BitWidth = AndRHSMask.getBitWidth();
4085 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4086 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4087
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004088 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004089 if (!(A && A->isZero()) && // avoid infinite recursion.
4090 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohman4ae51262009-08-12 16:23:25 +00004091 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004092 InsertNewInstBefore(NewNeg, I);
4093 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4094 }
4095 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004096 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004097
4098 case Instruction::Shl:
4099 case Instruction::LShr:
4100 // (1 << x) & 1 --> zext(x == 0)
4101 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004102 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004103 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004104 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004105 InsertNewInstBefore(NewICmp, I);
4106 return new ZExtInst(NewICmp, I.getType());
4107 }
4108 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004109 }
4110
Chris Lattner58403262003-07-23 19:25:52 +00004111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004112 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004113 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004115 // If this is an integer truncation or change from signed-to-unsigned, and
4116 // if the source is an and/or with immediate, transform it. This
4117 // frequently occurs for bitfield accesses.
4118 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004119 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004120 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004121 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004122 if (CastOp->getOpcode() == Instruction::And) {
4123 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4125 // This will fold the two constants together, which may allow
4126 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004127 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004128 CastOp->getOperand(0), I.getType(),
4129 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004130 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004131 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004132 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004133 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4134 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 } else if (CastOp->getOpcode() == Instruction::Or) {
4137 // Change: and (cast (or X, C1) to T), C2
4138 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004139 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004140 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4141 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004142 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004143 return ReplaceInstUsesWith(I, AndRHS);
4144 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004145 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004146 }
Chris Lattner06782f82003-07-23 19:36:21 +00004147 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004148
4149 // Try to fold constant and into select arguments.
4150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004152 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004153 if (isa<PHINode>(Op0))
4154 if (Instruction *NV = FoldOpIntoPhi(I))
4155 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004156 }
4157
Dan Gohman186a6362009-08-12 16:04:34 +00004158 Value *Op0NotVal = dyn_castNotVal(Op0);
4159 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004160
Chris Lattner5b62aa72004-06-18 06:07:51 +00004161 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004163
Misha Brukmancb6267b2004-07-30 12:50:08 +00004164 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004165 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004166 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004167 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004168 InsertNewInstBefore(Or, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004169 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004170 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004171
4172 {
Chris Lattner003b6202007-06-15 05:58:24 +00004173 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004174 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004175 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4176 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004177
4178 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004179 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004180 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004181 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004182 }
4183 }
4184
Dan Gohman4ae51262009-08-12 16:23:25 +00004185 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004186 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4187 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004188
4189 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004190 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004191 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004192 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004193 }
4194 }
Chris Lattner64daab52006-04-01 08:03:55 +00004195
4196 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004197 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004198 if (A == Op1) { // (A^B)&A -> A&(A^B)
4199 I.swapOperands(); // Simplify below
4200 std::swap(Op0, Op1);
4201 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4202 cast<BinaryOperator>(Op0)->swapOperands();
4203 I.swapOperands(); // Simplify below
4204 std::swap(Op0, Op1);
4205 }
4206 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004207
Chris Lattner64daab52006-04-01 08:03:55 +00004208 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004209 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004210 if (B == Op0) { // B&(A^B) -> B&(B^A)
4211 cast<BinaryOperator>(Op1)->swapOperands();
4212 std::swap(A, B);
4213 }
4214 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00004215 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004216 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004217 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004218 }
4219 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004220
4221 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004222 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4223 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004224 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004225 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4226 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004227 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004228 }
4229
Reid Spencere4d87aa2006-12-23 06:05:41 +00004230 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4231 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004232 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004233 return R;
4234
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004235 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4236 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4237 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004238 }
4239
Chris Lattner6fc205f2006-05-05 06:39:07 +00004240 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004241 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4244 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004245 if (SrcTy == Op1C->getOperand(0)->getType() &&
4246 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004247 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004248 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4249 I.getType(), TD) &&
4250 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4251 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004252 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004253 Op1C->getOperand(0),
4254 I.getName());
4255 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004256 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004257 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004258 }
Chris Lattnere511b742006-11-14 07:46:50 +00004259
4260 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004261 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4262 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4263 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004264 SI0->getOperand(1) == SI1->getOperand(1) &&
4265 (SI0->hasOneUse() || SI1->hasOneUse())) {
4266 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004267 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004268 SI1->getOperand(0),
4269 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004270 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004271 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004272 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004273 }
4274
Evan Cheng8db90722008-10-14 17:15:11 +00004275 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004276 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004277 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4278 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4279 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004280 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004281
Chris Lattner7e708292002-06-25 16:13:24 +00004282 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004283}
4284
Chris Lattner8c34cd22008-10-05 02:13:19 +00004285/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4286/// capable of providing pieces of a bswap. The subexpression provides pieces
4287/// of a bswap if it is proven that each of the non-zero bytes in the output of
4288/// the expression came from the corresponding "byte swapped" byte in some other
4289/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4290/// we know that the expression deposits the low byte of %X into the high byte
4291/// of the bswap result and that all other bytes are zero. This expression is
4292/// accepted, the high byte of ByteValues is set to X to indicate a correct
4293/// match.
4294///
4295/// This function returns true if the match was unsuccessful and false if so.
4296/// On entry to the function the "OverallLeftShift" is a signed integer value
4297/// indicating the number of bytes that the subexpression is later shifted. For
4298/// example, if the expression is later right shifted by 16 bits, the
4299/// OverallLeftShift value would be -2 on entry. This is used to specify which
4300/// byte of ByteValues is actually being set.
4301///
4302/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4303/// byte is masked to zero by a user. For example, in (X & 255), X will be
4304/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4305/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4306/// always in the local (OverallLeftShift) coordinate space.
4307///
4308static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4309 SmallVector<Value*, 8> &ByteValues) {
4310 if (Instruction *I = dyn_cast<Instruction>(V)) {
4311 // If this is an or instruction, it may be an inner node of the bswap.
4312 if (I->getOpcode() == Instruction::Or) {
4313 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4314 ByteValues) ||
4315 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4316 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004317 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004318
4319 // If this is a logical shift by a constant multiple of 8, recurse with
4320 // OverallLeftShift and ByteMask adjusted.
4321 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4322 unsigned ShAmt =
4323 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4324 // Ensure the shift amount is defined and of a byte value.
4325 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4326 return true;
4327
4328 unsigned ByteShift = ShAmt >> 3;
4329 if (I->getOpcode() == Instruction::Shl) {
4330 // X << 2 -> collect(X, +2)
4331 OverallLeftShift += ByteShift;
4332 ByteMask >>= ByteShift;
4333 } else {
4334 // X >>u 2 -> collect(X, -2)
4335 OverallLeftShift -= ByteShift;
4336 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004337 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004338 }
4339
4340 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4341 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4342
4343 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4344 ByteValues);
4345 }
4346
4347 // If this is a logical 'and' with a mask that clears bytes, clear the
4348 // corresponding bytes in ByteMask.
4349 if (I->getOpcode() == Instruction::And &&
4350 isa<ConstantInt>(I->getOperand(1))) {
4351 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4352 unsigned NumBytes = ByteValues.size();
4353 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4354 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4355
4356 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4357 // If this byte is masked out by a later operation, we don't care what
4358 // the and mask is.
4359 if ((ByteMask & (1 << i)) == 0)
4360 continue;
4361
4362 // If the AndMask is all zeros for this byte, clear the bit.
4363 APInt MaskB = AndMask & Byte;
4364 if (MaskB == 0) {
4365 ByteMask &= ~(1U << i);
4366 continue;
4367 }
4368
4369 // If the AndMask is not all ones for this byte, it's not a bytezap.
4370 if (MaskB != Byte)
4371 return true;
4372
4373 // Otherwise, this byte is kept.
4374 }
4375
4376 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4377 ByteValues);
4378 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004379 }
4380
Chris Lattner8c34cd22008-10-05 02:13:19 +00004381 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4382 // the input value to the bswap. Some observations: 1) if more than one byte
4383 // is demanded from this input, then it could not be successfully assembled
4384 // into a byteswap. At least one of the two bytes would not be aligned with
4385 // their ultimate destination.
4386 if (!isPowerOf2_32(ByteMask)) return true;
4387 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004388
Chris Lattner8c34cd22008-10-05 02:13:19 +00004389 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4390 // is demanded, it needs to go into byte 0 of the result. This means that the
4391 // byte needs to be shifted until it lands in the right byte bucket. The
4392 // shift amount depends on the position: if the byte is coming from the high
4393 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4394 // low part, it must be shifted left.
4395 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4396 if (InputByteNo < ByteValues.size()/2) {
4397 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4398 return true;
4399 } else {
4400 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4401 return true;
4402 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004403
4404 // If the destination byte value is already defined, the values are or'd
4405 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004406 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004407 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004408 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409 return false;
4410}
4411
4412/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4413/// If so, insert the new bswap intrinsic and return it.
4414Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004415 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004416 if (!ITy || ITy->getBitWidth() % 16 ||
4417 // ByteMask only allows up to 32-byte values.
4418 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004419 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004420
4421 /// ByteValues - For each byte of the result, we keep track of which value
4422 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004423 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004424 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425
4426 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004427 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4428 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429 return 0;
4430
4431 // Check to see if all of the bytes come from the same value.
4432 Value *V = ByteValues[0];
4433 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4434
4435 // Check to make sure that all of the bytes come from the same value.
4436 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4437 if (ByteValues[i] != V)
4438 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004439 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004440 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004441 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004442 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004443}
4444
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004445/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4446/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4447/// we can simplify this expression to "cond ? C : D or B".
4448static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004449 Value *C, Value *D,
4450 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004451 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004452 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004453 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004454 return 0;
4455
Chris Lattnera6a474d2008-11-16 04:26:55 +00004456 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004457 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004458 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004459 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004460 return SelectInst::Create(Cond, C, B);
4461 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004462 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004463 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004464 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004466 return 0;
4467}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004468
Chris Lattner69d4ced2008-11-16 05:20:07 +00004469/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4470Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4471 ICmpInst *LHS, ICmpInst *RHS) {
4472 Value *Val, *Val2;
4473 ConstantInt *LHSCst, *RHSCst;
4474 ICmpInst::Predicate LHSCC, RHSCC;
4475
4476 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004477 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004478 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004479 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004480 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004481 return 0;
4482
4483 // From here on, we only handle:
4484 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4485 if (Val != Val2) return 0;
4486
4487 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4488 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4489 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4490 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4491 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4492 return 0;
4493
4494 // We can't fold (ugt x, C) | (sgt x, C2).
4495 if (!PredicatesFoldable(LHSCC, RHSCC))
4496 return 0;
4497
4498 // Ensure that the larger constant is on the RHS.
4499 bool ShouldSwap;
4500 if (ICmpInst::isSignedPredicate(LHSCC) ||
4501 (ICmpInst::isEquality(LHSCC) &&
4502 ICmpInst::isSignedPredicate(RHSCC)))
4503 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4504 else
4505 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4506
4507 if (ShouldSwap) {
4508 std::swap(LHS, RHS);
4509 std::swap(LHSCst, RHSCst);
4510 std::swap(LHSCC, RHSCC);
4511 }
4512
4513 // At this point, we know we have have two icmp instructions
4514 // comparing a value against two constants and or'ing the result
4515 // together. Because of the above check, we know that we only have
4516 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4517 // FoldICmpLogical check above), that the two constants are not
4518 // equal.
4519 assert(LHSCst != RHSCst && "Compares not folded above?");
4520
4521 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004522 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 case ICmpInst::ICMP_EQ:
4524 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004525 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004526 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004527 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004528 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004529 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004530 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4531 Val->getName()+".off");
4532 InsertNewInstBefore(Add, I);
Dan Gohman186a6362009-08-12 16:04:34 +00004533 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004534 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004535 }
4536 break; // (X == 13 | X == 15) -> no change
4537 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4538 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4539 break;
4540 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4541 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4542 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4543 return ReplaceInstUsesWith(I, RHS);
4544 }
4545 break;
4546 case ICmpInst::ICMP_NE:
4547 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004548 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004549 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4550 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4551 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4552 return ReplaceInstUsesWith(I, LHS);
4553 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4554 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4555 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004556 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004557 }
4558 break;
4559 case ICmpInst::ICMP_ULT:
4560 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004561 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004562 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4563 break;
4564 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4565 // If RHSCst is [us]MAXINT, it is always false. Not handling
4566 // this can cause overflow.
4567 if (RHSCst->isMaxValue(false))
4568 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004569 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004570 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4572 break;
4573 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4574 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4575 return ReplaceInstUsesWith(I, RHS);
4576 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4577 break;
4578 }
4579 break;
4580 case ICmpInst::ICMP_SLT:
4581 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004582 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004583 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4584 break;
4585 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4586 // If RHSCst is [us]MAXINT, it is always false. Not handling
4587 // this can cause overflow.
4588 if (RHSCst->isMaxValue(true))
4589 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004590 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004591 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4593 break;
4594 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4595 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4596 return ReplaceInstUsesWith(I, RHS);
4597 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4598 break;
4599 }
4600 break;
4601 case ICmpInst::ICMP_UGT:
4602 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004603 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004604 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4605 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4606 return ReplaceInstUsesWith(I, LHS);
4607 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4608 break;
4609 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4610 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004611 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004612 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4613 break;
4614 }
4615 break;
4616 case ICmpInst::ICMP_SGT:
4617 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004618 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4620 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4621 return ReplaceInstUsesWith(I, LHS);
4622 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4623 break;
4624 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4625 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004626 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004627 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4628 break;
4629 }
4630 break;
4631 }
4632 return 0;
4633}
4634
Chris Lattner5414cc52009-07-23 05:46:22 +00004635Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4636 FCmpInst *RHS) {
4637 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4638 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4639 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4640 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4641 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4642 // If either of the constants are nans, then the whole thing returns
4643 // true.
4644 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004645 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004646
4647 // Otherwise, no need to compare the two constants, compare the
4648 // rest.
4649 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4650 LHS->getOperand(0), RHS->getOperand(0));
4651 }
4652
4653 // Handle vector zeros. This occurs because the canonical form of
4654 // "fcmp uno x,x" is "fcmp uno x, 0".
4655 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4656 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4657 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4658 LHS->getOperand(0), RHS->getOperand(0));
4659
4660 return 0;
4661 }
4662
4663 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4664 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4665 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4666
4667 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4668 // Swap RHS operands to match LHS.
4669 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4670 std::swap(Op1LHS, Op1RHS);
4671 }
4672 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4673 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4674 if (Op0CC == Op1CC)
4675 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4676 Op0LHS, Op0RHS);
4677 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004678 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004679 if (Op0CC == FCmpInst::FCMP_FALSE)
4680 return ReplaceInstUsesWith(I, RHS);
4681 if (Op1CC == FCmpInst::FCMP_FALSE)
4682 return ReplaceInstUsesWith(I, LHS);
4683 bool Op0Ordered;
4684 bool Op1Ordered;
4685 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4686 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4687 if (Op0Ordered == Op1Ordered) {
4688 // If both are ordered or unordered, return a new fcmp with
4689 // or'ed predicates.
4690 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4691 Op0LHS, Op0RHS, Context);
4692 if (Instruction *I = dyn_cast<Instruction>(RV))
4693 return I;
4694 // Otherwise, it's a constant boolean value...
4695 return ReplaceInstUsesWith(I, RV);
4696 }
4697 }
4698 return 0;
4699}
4700
Bill Wendlinga698a472008-12-01 08:23:25 +00004701/// FoldOrWithConstants - This helper function folds:
4702///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004703/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004704///
4705/// into:
4706///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004707/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004708///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004709/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004710Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004711 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004712 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4713 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004714
Bill Wendling286a0542008-12-02 06:24:20 +00004715 Value *V1 = 0;
4716 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004717 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004718
Bill Wendling29976b92008-12-02 06:18:11 +00004719 APInt Xor = CI1->getValue() ^ CI2->getValue();
4720 if (!Xor.isAllOnesValue()) return 0;
4721
Bill Wendling286a0542008-12-02 06:24:20 +00004722 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004723 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004724 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4725 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004726 }
4727
4728 return 0;
4729}
4730
Chris Lattner7e708292002-06-25 16:13:24 +00004731Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004732 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004733 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004734
Chris Lattner42593e62007-03-24 23:56:43 +00004735 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004736 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004737
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004738 // or X, X = X
4739 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004740 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004741
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004742 // See if we can simplify any instructions used by the instruction whose sole
4743 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004744 if (SimplifyDemandedInstructionBits(I))
4745 return &I;
4746 if (isa<VectorType>(I.getType())) {
4747 if (isa<ConstantAggregateZero>(Op1)) {
4748 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4749 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4750 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4751 return ReplaceInstUsesWith(I, I.getOperand(1));
4752 }
Chris Lattner42593e62007-03-24 23:56:43 +00004753 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004754
Chris Lattner3f5b8772002-05-06 16:14:14 +00004755 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004756 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004757 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004758 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004759 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004760 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004761 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004762 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004763 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004764 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004765 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004766 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004767
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004768 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004769 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004770 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::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004775 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004776 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004777
4778 // Try to fold constant and into select arguments.
4779 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004780 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004781 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004782 if (isa<PHINode>(Op0))
4783 if (Instruction *NV = FoldOpIntoPhi(I))
4784 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004785 }
4786
Chris Lattner4f637d42006-01-06 17:59:59 +00004787 Value *A = 0, *B = 0;
4788 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004789
Dan Gohman4ae51262009-08-12 16:23:25 +00004790 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004791 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4792 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004793 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004794 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4795 return ReplaceInstUsesWith(I, Op0);
4796
Chris Lattner6423d4c2006-07-10 20:25:24 +00004797 // (A | B) | C and A | (B | C) -> bswap if possible.
4798 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004799 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4800 match(Op1, m_Or(m_Value(), m_Value())) ||
4801 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4802 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004803 if (Instruction *BSwap = MatchBSwap(I))
4804 return BSwap;
4805 }
4806
Chris Lattner6e4c6492005-05-09 04:58:36 +00004807 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004808 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004809 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004810 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004811 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004812 InsertNewInstBefore(NOr, I);
4813 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004814 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004815 }
4816
4817 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004818 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004819 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004820 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004821 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
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
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004827 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004828 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004829 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4830 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004831 Value *V1 = 0, *V2 = 0, *V3 = 0;
4832 C1 = dyn_cast<ConstantInt>(C);
4833 C2 = dyn_cast<ConstantInt>(D);
4834 if (C1 && C2) { // (A & C1)|(B & C2)
4835 // If we have: ((V + N) & C1) | (V & C2)
4836 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4837 // replace with V+N.
4838 if (C1->getValue() == ~C2->getValue()) {
4839 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004840 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004841 // Add commutes, try both ways.
4842 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4843 return ReplaceInstUsesWith(I, A);
4844 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4845 return ReplaceInstUsesWith(I, A);
4846 }
4847 // Or commutes, try both ways.
4848 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004849 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004850 // Add commutes, try both ways.
4851 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4852 return ReplaceInstUsesWith(I, B);
4853 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4854 return ReplaceInstUsesWith(I, B);
4855 }
4856 }
Chris Lattner044e5332007-04-08 08:01:49 +00004857 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004858 }
4859
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004860 // Check to see if we have any common things being and'ed. If so, find the
4861 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004862 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4863 if (A == B) // (A & C)|(A & D) == A & (C|D)
4864 V1 = A, V2 = C, V3 = D;
4865 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4866 V1 = A, V2 = B, V3 = C;
4867 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4868 V1 = C, V2 = A, V3 = D;
4869 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4870 V1 = C, V2 = A, V3 = B;
4871
4872 if (V1) {
4873 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004874 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4875 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004876 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004877 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004878
Dan Gohman1975d032008-10-30 20:40:10 +00004879 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004880 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004881 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004882 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004883 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004884 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004885 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004886 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004887 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004888
Bill Wendlingb01865c2008-11-30 13:52:49 +00004889 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004890 if ((match(C, m_Not(m_Specific(D))) &&
4891 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004892 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004893 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004894 if ((match(A, m_Not(m_Specific(D))) &&
4895 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004896 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004897 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004898 if ((match(C, m_Not(m_Specific(B))) &&
4899 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004900 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004901 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004902 if ((match(A, m_Not(m_Specific(B))) &&
4903 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004904 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004905 }
Chris Lattnere511b742006-11-14 07:46:50 +00004906
4907 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004908 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4909 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4910 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004911 SI0->getOperand(1) == SI1->getOperand(1) &&
4912 (SI0->hasOneUse() || SI1->hasOneUse())) {
4913 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004914 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004915 SI1->getOperand(0),
4916 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004917 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004918 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004919 }
4920 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004921
Bill Wendlingb3833d12008-12-01 01:07:11 +00004922 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004923 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4924 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004925 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004926 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004927 }
4928 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004929 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4930 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004931 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004932 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004933 }
4934
Dan Gohman4ae51262009-08-12 16:23:25 +00004935 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004936 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004937 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004938 } else {
4939 A = 0;
4940 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004941 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004942 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004943 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004944 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004945
Misha Brukmancb6267b2004-07-30 12:50:08 +00004946 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004947 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004948 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004949 I.getName()+".demorgan"), I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004950 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004951 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004952 }
Chris Lattnera2881962003-02-18 19:28:33 +00004953
Reid Spencere4d87aa2006-12-23 06:05:41 +00004954 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4955 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004956 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004957 return R;
4958
Chris Lattner69d4ced2008-11-16 05:20:07 +00004959 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4960 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4961 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004962 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004963
4964 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004965 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004966 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004967 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004968 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4969 !isa<ICmpInst>(Op1C->getOperand(0))) {
4970 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004971 if (SrcTy == Op1C->getOperand(0)->getType() &&
4972 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004973 // Only do this if the casts both really cause code to be
4974 // generated.
4975 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4976 I.getType(), TD) &&
4977 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4978 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004979 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004980 Op1C->getOperand(0),
4981 I.getName());
4982 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004983 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004984 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004985 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004986 }
Chris Lattner99c65742007-10-24 05:38:08 +00004987 }
4988
4989
4990 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4991 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004992 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4993 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4994 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004995 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004996
Chris Lattner7e708292002-06-25 16:13:24 +00004997 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004998}
4999
Dan Gohman844731a2008-05-13 00:00:25 +00005000namespace {
5001
Chris Lattnerc317d392004-02-16 01:20:27 +00005002// XorSelf - Implements: X ^ X --> 0
5003struct XorSelf {
5004 Value *RHS;
5005 XorSelf(Value *rhs) : RHS(rhs) {}
5006 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5007 Instruction *apply(BinaryOperator &Xor) const {
5008 return &Xor;
5009 }
5010};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005011
Dan Gohman844731a2008-05-13 00:00:25 +00005012}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005013
Chris Lattner7e708292002-06-25 16:13:24 +00005014Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005015 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005017
Evan Chengd34af782008-03-25 20:07:13 +00005018 if (isa<UndefValue>(Op1)) {
5019 if (isa<UndefValue>(Op0))
5020 // Handle undef ^ undef -> 0 special case. This is a common
5021 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005022 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005023 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005024 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005025
Chris Lattnerc317d392004-02-16 01:20:27 +00005026 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005027 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005028 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005029 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005030 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005031
5032 // See if we can simplify any instructions used by the instruction whose sole
5033 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005034 if (SimplifyDemandedInstructionBits(I))
5035 return &I;
5036 if (isa<VectorType>(I.getType()))
5037 if (isa<ConstantAggregateZero>(Op1))
5038 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005039
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005040 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005041 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005042 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5043 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5044 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5045 if (Op0I->getOpcode() == Instruction::And ||
5046 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005047 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5048 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005049 Instruction *NotY =
Dan Gohman4ae51262009-08-12 16:23:25 +00005050 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005051 Op0I->getOperand(1)->getName()+".not");
5052 InsertNewInstBefore(NotY, I);
5053 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005054 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005055 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005056 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005057 }
5058 }
5059 }
5060 }
5061
5062
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005063 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005064 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005065 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005066 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005067 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005069
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005070 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005071 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005072 FCI->getOperand(0), FCI->getOperand(1));
5073 }
5074
Nick Lewycky517e1f52008-05-31 19:01:33 +00005075 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5076 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5077 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5078 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5079 Instruction::CastOps Opcode = Op0C->getOpcode();
5080 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005081 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005082 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005083 Op0C->getDestTy())) {
5084 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005085 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005086 CI->getOpcode(), CI->getInversePredicate(),
5087 CI->getOperand(0), CI->getOperand(1)), I);
5088 NewCI->takeName(CI);
5089 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5090 }
5091 }
5092 }
5093 }
5094 }
5095
Reid Spencere4d87aa2006-12-23 06:05:41 +00005096 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005097 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005098 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5099 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005100 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5101 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005102 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005103 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005104 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005105
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005106 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005107 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005108 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005109 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005110 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005111 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005112 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005113 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005114 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005115 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005116 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005117 Constant *C = ConstantInt::get(*Context,
5118 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005119 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005120
Chris Lattner7c4049c2004-01-12 19:35:11 +00005121 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005122 } else if (Op0I->getOpcode() == Instruction::Or) {
5123 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005124 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005125 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005126 // Anything in both C1 and C2 is known to be zero, remove it from
5127 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005128 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5129 NewRHS = ConstantExpr::getAnd(NewRHS,
5130 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005131 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005132 I.setOperand(0, Op0I->getOperand(0));
5133 I.setOperand(1, NewRHS);
5134 return &I;
5135 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005136 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005137 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005138 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005139
5140 // Try to fold constant and into select arguments.
5141 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005142 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005143 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005144 if (isa<PHINode>(Op0))
5145 if (Instruction *NV = FoldOpIntoPhi(I))
5146 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005147 }
5148
Dan Gohman186a6362009-08-12 16:04:34 +00005149 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005150 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005151 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005152
Dan Gohman186a6362009-08-12 16:04:34 +00005153 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005154 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005155 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005156
Chris Lattner318bf792007-03-18 22:51:34 +00005157
5158 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5159 if (Op1I) {
5160 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005161 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005162 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005163 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005164 I.swapOperands();
5165 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005166 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005167 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005168 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005169 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005170 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005171 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005172 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005173 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005174 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005175 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005176 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005177 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005178 std::swap(A, B);
5179 }
Chris Lattner318bf792007-03-18 22:51:34 +00005180 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005181 I.swapOperands(); // Simplified below.
5182 std::swap(Op0, Op1);
5183 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005184 }
Chris Lattner318bf792007-03-18 22:51:34 +00005185 }
5186
5187 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5188 if (Op0I) {
5189 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005190 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005191 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005192 if (A == Op1) // (B|A)^B == (A|B)^B
5193 std::swap(A, B);
5194 if (B == Op1) { // (A|B)^B == A & ~B
5195 Instruction *NotB =
Dan Gohman4ae51262009-08-12 16:23:25 +00005196 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005197 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005198 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005199 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005200 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005201 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005202 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005203 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005204 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005205 if (A == Op1) // (A&B)^A -> (B&A)^A
5206 std::swap(A, B);
5207 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005208 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005209 Instruction *N =
Dan Gohman4ae51262009-08-12 16:23:25 +00005210 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005211 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005212 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005213 }
Chris Lattner318bf792007-03-18 22:51:34 +00005214 }
5215
5216 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5217 if (Op0I && Op1I && Op0I->isShift() &&
5218 Op0I->getOpcode() == Op1I->getOpcode() &&
5219 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5220 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5221 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005222 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005223 Op1I->getOperand(0),
5224 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005225 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005226 Op1I->getOperand(1));
5227 }
5228
5229 if (Op0I && Op1I) {
5230 Value *A, *B, *C, *D;
5231 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005232 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5233 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005234 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005235 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005236 }
5237 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005238 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5239 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005240 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005241 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005242 }
5243
5244 // (A & B)^(C & D)
5245 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005246 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5247 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005248 // (X & Y)^(X & Y) -> (Y^Z) & X
5249 Value *X = 0, *Y = 0, *Z = 0;
5250 if (A == C)
5251 X = A, Y = B, Z = D;
5252 else if (A == D)
5253 X = A, Y = B, Z = C;
5254 else if (B == C)
5255 X = B, Y = A, Z = D;
5256 else if (B == D)
5257 X = B, Y = A, Z = C;
5258
5259 if (X) {
5260 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005261 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5262 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005263 }
5264 }
5265 }
5266
Reid Spencere4d87aa2006-12-23 06:05:41 +00005267 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5268 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005269 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005270 return R;
5271
Chris Lattner6fc205f2006-05-05 06:39:07 +00005272 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005273 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005274 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005275 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5276 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005277 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005278 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005279 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5280 I.getType(), TD) &&
5281 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5282 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005283 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005284 Op1C->getOperand(0),
5285 I.getName());
5286 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005287 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005288 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005289 }
Chris Lattner99c65742007-10-24 05:38:08 +00005290 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005291
Chris Lattner7e708292002-06-25 16:13:24 +00005292 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005293}
5294
Owen Andersond672ecb2009-07-03 00:17:18 +00005295static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005296 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005297 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005298}
Chris Lattnera96879a2004-09-29 17:40:11 +00005299
Dan Gohman6de29f82009-06-15 22:12:54 +00005300static bool HasAddOverflow(ConstantInt *Result,
5301 ConstantInt *In1, ConstantInt *In2,
5302 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005303 if (IsSigned)
5304 if (In2->getValue().isNegative())
5305 return Result->getValue().sgt(In1->getValue());
5306 else
5307 return Result->getValue().slt(In1->getValue());
5308 else
5309 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005310}
5311
Dan Gohman6de29f82009-06-15 22:12:54 +00005312/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005313/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005314static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005315 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005316 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005317 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005318
Dan Gohman6de29f82009-06-15 22:12:54 +00005319 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5320 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005321 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005322 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5323 ExtractElement(In1, Idx, Context),
5324 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005325 IsSigned))
5326 return true;
5327 }
5328 return false;
5329 }
5330
5331 return HasAddOverflow(cast<ConstantInt>(Result),
5332 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5333 IsSigned);
5334}
5335
5336static bool HasSubOverflow(ConstantInt *Result,
5337 ConstantInt *In1, ConstantInt *In2,
5338 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005339 if (IsSigned)
5340 if (In2->getValue().isNegative())
5341 return Result->getValue().slt(In1->getValue());
5342 else
5343 return Result->getValue().sgt(In1->getValue());
5344 else
5345 return Result->getValue().ugt(In1->getValue());
5346}
5347
Dan Gohman6de29f82009-06-15 22:12:54 +00005348/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5349/// overflowed for this type.
5350static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005351 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005352 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005353 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005354
5355 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5356 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005357 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005358 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5359 ExtractElement(In1, Idx, Context),
5360 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005361 IsSigned))
5362 return true;
5363 }
5364 return false;
5365 }
5366
5367 return HasSubOverflow(cast<ConstantInt>(Result),
5368 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5369 IsSigned);
5370}
5371
Chris Lattner574da9b2005-01-13 20:14:25 +00005372/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5373/// code necessary to compute the offset from the base pointer (without adding
5374/// in the base pointer). Return the result as a signed integer of intptr size.
5375static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005376 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005377 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005378 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005379 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005380 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005381
5382 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005383 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005384 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005385
Gabor Greif177dd3f2008-06-12 21:37:33 +00005386 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5387 ++i, ++GTI) {
5388 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005389 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005390 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5391 if (OpC->isZero()) continue;
5392
5393 // Handle a struct index, which adds its field offset to the pointer.
5394 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5395 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5396
5397 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005398 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005399 ConstantInt::get(*Context,
5400 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005401 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005402 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005403 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005404 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005405 GEP->getName()+".offs"), I);
5406 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005407 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005408
Owen Andersoneed707b2009-07-24 23:12:02 +00005409 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005410 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005411 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005414 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 else {
5416 // Emit an add instruction.
5417 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005418 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005420 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005422 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 // Convert to correct type.
5424 if (Op->getType() != IntPtrTy) {
5425 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005426 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005428 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429 true,
5430 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 }
5432 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005433 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005434 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005435 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005436 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005437 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005438 GEP->getName()+".idx"), I);
5439 }
5440
5441 // Emit an add instruction.
5442 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005443 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 cast<Constant>(Result));
5445 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005446 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005448 }
5449 return Result;
5450}
5451
Chris Lattner10c0d912008-04-22 02:53:33 +00005452
Dan Gohman8f080f02009-07-17 22:16:21 +00005453/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5454/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5455/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5456/// be complex, and scales are involved. The above expression would also be
5457/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5458/// This later form is less amenable to optimization though, and we are allowed
5459/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005460///
5461/// If we can't emit an optimized form for this expression, this returns null.
5462///
5463static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005465 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005466 gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468 // Check to see if this gep only has a single variable index. If so, and if
5469 // any constant indices are a multiple of its scale, then we can compute this
5470 // in terms of the scale of the variable index. For example, if the GEP
5471 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472 // because the expression will cross zero at the same point.
5473 unsigned i, e = GEP->getNumOperands();
5474 int64_t Offset = 0;
5475 for (i = 1; i != e; ++i, ++GTI) {
5476 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477 // Compute the aggregate offset of constant indices.
5478 if (CI->isZero()) continue;
5479
5480 // Handle a struct index, which adds its field offset to the pointer.
5481 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005484 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005485 Offset += Size*CI->getSExtValue();
5486 }
5487 } else {
5488 // Found our variable index.
5489 break;
5490 }
5491 }
5492
5493 // If there are no variable indices, we must have a constant offset, just
5494 // evaluate it the general way.
5495 if (i == e) return 0;
5496
5497 Value *VariableIdx = GEP->getOperand(i);
5498 // Determine the scale factor of the variable element. For example, this is
5499 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005500 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005501
5502 // Verify that there are no other variable indices. If so, emit the hard way.
5503 for (++i, ++GTI; i != e; ++i, ++GTI) {
5504 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505 if (!CI) return 0;
5506
5507 // Compute the aggregate offset of constant indices.
5508 if (CI->isZero()) continue;
5509
5510 // Handle a struct index, which adds its field offset to the pointer.
5511 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005514 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005515 Offset += Size*CI->getSExtValue();
5516 }
5517 }
5518
5519 // Okay, we know we have a single variable index, which must be a
5520 // pointer/array/vector index. If there is no offset, life is simple, return
5521 // the index.
5522 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523 if (Offset == 0) {
5524 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5525 // we don't need to bother extending: the extension won't affect where the
5526 // computation crosses zero.
5527 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005529 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005530 return VariableIdx;
5531 }
5532
5533 // Otherwise, there is an index. The computation we will do will be modulo
5534 // the pointer size, so get it.
5535 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536
5537 Offset &= PtrSizeMask;
5538 VariableScale &= PtrSizeMask;
5539
5540 // To do this transformation, any constant index must be a multiple of the
5541 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5542 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5543 // multiple of the variable scale.
5544 int64_t NewOffs = Offset / (int64_t)VariableScale;
5545 if (Offset != NewOffs*(int64_t)VariableScale)
5546 return 0;
5547
5548 // Okay, we can do this evaluation. Start by converting the index to intptr.
5549 const Type *IntPtrTy = TD.getIntPtrType();
5550 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005551 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005552 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005553 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005554 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005555 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005556}
5557
5558
Reid Spencere4d87aa2006-12-23 06:05:41 +00005559/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005560/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005561Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005562 ICmpInst::Predicate Cond,
5563 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005564 // Look through bitcasts.
5565 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5566 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005567
Chris Lattner574da9b2005-01-13 20:14:25 +00005568 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005569 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005570 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005571 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005572 // know pointers can't overflow since the gep is inbounds. See if we can
5573 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005574 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5575
5576 // If not, synthesize the offset the hard way.
5577 if (Offset == 0)
5578 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005579 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005580 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005581 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005582 // If the base pointers are different, but the indices are the same, just
5583 // compare the base pointer.
5584 if (PtrBase != GEPRHS->getOperand(0)) {
5585 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005586 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005587 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005588 if (IndicesTheSame)
5589 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5590 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5591 IndicesTheSame = false;
5592 break;
5593 }
5594
5595 // If all indices are the same, just compare the base pointers.
5596 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005597 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005598 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005599
5600 // Otherwise, the base pointers are different and the indices are
5601 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005602 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005603 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005604
Chris Lattnere9d782b2005-01-13 22:25:21 +00005605 // If one of the GEPs has all zero indices, recurse.
5606 bool AllZeros = true;
5607 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5608 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5609 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5610 AllZeros = false;
5611 break;
5612 }
5613 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005614 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5615 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005616
5617 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005618 AllZeros = true;
5619 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5620 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5621 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5622 AllZeros = false;
5623 break;
5624 }
5625 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005626 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005627
Chris Lattner4401c9c2005-01-14 00:20:05 +00005628 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5629 // If the GEPs only differ by one index, compare it.
5630 unsigned NumDifferences = 0; // Keep track of # differences.
5631 unsigned DiffOperand = 0; // The operand that differs.
5632 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5633 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005634 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5635 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005636 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005637 NumDifferences = 2;
5638 break;
5639 } else {
5640 if (NumDifferences++) break;
5641 DiffOperand = i;
5642 }
5643 }
5644
5645 if (NumDifferences == 0) // SAME GEP?
5646 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneed707b2009-07-24 23:12:02 +00005647 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005648 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005649
Chris Lattner4401c9c2005-01-14 00:20:05 +00005650 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005651 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5652 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005653 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005654 return new ICmpInst(*Context,
5655 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005656 }
5657 }
5658
Reid Spencere4d87aa2006-12-23 06:05:41 +00005659 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005660 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005661 if (TD &&
5662 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005663 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5665 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005667 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005668 }
5669 }
5670 return 0;
5671}
5672
Chris Lattnera5406232008-05-19 20:18:56 +00005673/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674///
5675Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676 Instruction *LHSI,
5677 Constant *RHSC) {
5678 if (!isa<ConstantFP>(RHSC)) return 0;
5679 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680
5681 // Get the width of the mantissa. We don't want to hack on conversions that
5682 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005683 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005684 if (MantissaWidth == -1) return 0; // Unknown.
5685
5686 // Check to see that the input is converted from an integer type that is small
5687 // enough that preserves all bits. TODO: check here for "known" sign bits.
5688 // 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 +00005689 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005690
5691 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005692 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005694 ++InputSize;
5695
5696 // If the conversion would lose info, don't hack on this.
5697 if ((int)InputSize > MantissaWidth)
5698 return 0;
5699
5700 // Otherwise, we can potentially simplify the comparison. We know that it
5701 // will always come through as an integer value and we know the constant is
5702 // not a NAN (it would have been previously simplified).
5703 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704
5705 ICmpInst::Predicate Pred;
5706 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005707 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005708 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005709 case FCmpInst::FCMP_OEQ:
5710 Pred = ICmpInst::ICMP_EQ;
5711 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005713 case FCmpInst::FCMP_OGT:
5714 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_OGE:
5718 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OLT:
5722 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OLE:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_ONE:
5730 Pred = ICmpInst::ICMP_NE;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005735 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005736 }
5737
5738 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739
5740 // Now we know that the APFloat is a normal number, zero or inf.
5741
Chris Lattner85162782008-05-20 03:50:52 +00005742 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005743 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005744 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005745
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005746 if (!LHSUnsigned) {
5747 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5748 // and large values.
5749 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751 APFloat::rmNearestTiesToEven);
5752 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5753 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5754 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005755 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005757 }
5758 } else {
5759 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760 // +INF and large values.
5761 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763 APFloat::rmNearestTiesToEven);
5764 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5765 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5766 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005767 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5768 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005769 }
Chris Lattnera5406232008-05-19 20:18:56 +00005770 }
5771
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005772 if (!LHSUnsigned) {
5773 // See if the RHS value is < SignedMin.
5774 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776 APFloat::rmNearestTiesToEven);
5777 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005780 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5781 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005782 }
Chris Lattnera5406232008-05-19 20:18:56 +00005783 }
5784
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005785 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786 // [0, UMAX], but it may still be fractional. See if it is fractional by
5787 // casting the FP value to the integer value and back, checking for equality.
5788 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005789 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005790 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5791 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005792 if (!RHS.isZero()) {
5793 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005794 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5795 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005796 if (!Equal) {
5797 // If we had a comparison against a fractional value, we have to adjust
5798 // the compare predicate and sometimes the value. RHSC is rounded towards
5799 // zero at this point.
5800 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005801 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005802 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005803 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005804 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005805 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005806 case ICmpInst::ICMP_ULE:
5807 // (float)int <= 4.4 --> int <= 4
5808 // (float)int <= -4.4 --> false
5809 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005810 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005811 break;
5812 case ICmpInst::ICMP_SLE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> int < -4
5815 if (RHS.isNegative())
5816 Pred = ICmpInst::ICMP_SLT;
5817 break;
5818 case ICmpInst::ICMP_ULT:
5819 // (float)int < -4.4 --> false
5820 // (float)int < 4.4 --> int <= 4
5821 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005822 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005823 Pred = ICmpInst::ICMP_ULE;
5824 break;
5825 case ICmpInst::ICMP_SLT:
5826 // (float)int < -4.4 --> int < -4
5827 // (float)int < 4.4 --> int <= 4
5828 if (!RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SLE;
5830 break;
5831 case ICmpInst::ICMP_UGT:
5832 // (float)int > 4.4 --> int > 4
5833 // (float)int > -4.4 --> true
5834 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005835 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005836 break;
5837 case ICmpInst::ICMP_SGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> int >= -4
5840 if (RHS.isNegative())
5841 Pred = ICmpInst::ICMP_SGE;
5842 break;
5843 case ICmpInst::ICMP_UGE:
5844 // (float)int >= -4.4 --> true
5845 // (float)int >= 4.4 --> int > 4
5846 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005848 Pred = ICmpInst::ICMP_UGT;
5849 break;
5850 case ICmpInst::ICMP_SGE:
5851 // (float)int >= -4.4 --> int >= -4
5852 // (float)int >= 4.4 --> int > 4
5853 if (!RHS.isNegative())
5854 Pred = ICmpInst::ICMP_SGT;
5855 break;
5856 }
Chris Lattnera5406232008-05-19 20:18:56 +00005857 }
5858 }
5859
5860 // Lower this FP comparison into an appropriate integer version of the
5861 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005862 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005863}
5864
Reid Spencere4d87aa2006-12-23 06:05:41 +00005865Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005868
Chris Lattner58e97462007-01-14 19:42:17 +00005869 // Fold trivial predicates.
5870 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005871 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005872 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005873 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005874
5875 // Simplify 'fcmp pred X, X'
5876 if (Op0 == Op1) {
5877 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005878 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005879 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5880 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5881 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005883 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5884 case FCmpInst::FCMP_OLT: // True if ordered and less than
5885 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005887
5888 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5889 case FCmpInst::FCMP_ULT: // True if unordered or less than
5890 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5891 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5892 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005894 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005895 return &I;
5896
5897 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5898 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5899 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5900 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5901 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005903 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005904 return &I;
5905 }
5906 }
5907
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005909 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005910
Reid Spencere4d87aa2006-12-23 06:05:41 +00005911 // Handle fcmp with constant RHS
5912 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005913 // If the constant is a nan, see if we can fold the comparison based on it.
5914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915 if (CFP->getValueAPF().isNaN()) {
5916 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005917 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005918 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919 "Comparison must be either ordered or unordered!");
5920 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005922 }
5923 }
5924
Reid Spencere4d87aa2006-12-23 06:05:41 +00005925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926 switch (LHSI->getOpcode()) {
5927 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005928 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929 // block. If in the same block, we're encouraging jump threading. If
5930 // not, we are just pessimizing the code by making an i1 phi.
5931 if (LHSI->getParent() == I.getParent())
5932 if (Instruction *NV = FoldOpIntoPhi(I))
5933 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005935 case Instruction::SIToFP:
5936 case Instruction::UIToFP:
5937 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938 return NV;
5939 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 case Instruction::Select:
5941 // If either operand of the select is a constant, we can fold the
5942 // comparison into the select arms, which will cause one to be
5943 // constant folded and the select turned into a bitwise or.
5944 Value *Op1 = 0, *Op2 = 0;
5945 if (LHSI->hasOneUse()) {
5946 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005948 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005950 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005951 LHSI->getOperand(2), RHSC,
5952 I.getName()), I);
5953 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005955 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005956 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005957 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 LHSI->getOperand(1), RHSC,
5959 I.getName()), I);
5960 }
5961 }
5962
5963 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005964 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 break;
5966 }
5967 }
5968
5969 return Changed ? &I : 0;
5970}
5971
5972Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973 bool Changed = SimplifyCompare(I);
5974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975 const Type *Ty = Op0->getType();
5976
5977 // icmp X, X
5978 if (Op0 == Op1)
Owen Andersoneed707b2009-07-24 23:12:02 +00005979 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005980 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981
5982 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005983 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005984
Reid Spencere4d87aa2006-12-23 06:05:41 +00005985 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005986 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005987 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988 isa<ConstantPointerNull>(Op0)) &&
5989 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005990 isa<ConstantPointerNull>(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()));
Chris Lattner8b170942002-08-09 23:47:40 +00005993
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005995 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005997 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005998 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005999 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006000 InsertNewInstBefore(Xor, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00006001 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006002 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006003 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006004 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006005
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006007 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006008 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohman4ae51262009-08-12 16:23:25 +00006010 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006011 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006012 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006013 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006014 case ICmpInst::ICMP_SGT:
6015 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006016 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006018 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006019 InsertNewInstBefore(Not, I);
6020 return BinaryOperator::CreateAnd(Not, Op0);
6021 }
6022 case ICmpInst::ICMP_UGE:
6023 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6024 // FALL THROUGH
6025 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohman4ae51262009-08-12 16:23:25 +00006026 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006027 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006028 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006029 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SGE:
6031 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006034 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006035 InsertNewInstBefore(Not, I);
6036 return BinaryOperator::CreateOr(Not, Op0);
6037 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006038 }
Chris Lattner8b170942002-08-09 23:47:40 +00006039 }
6040
Dan Gohman1c8491e2009-04-25 17:12:48 +00006041 unsigned BitWidth = 0;
6042 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006043 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044 else if (Ty->isIntOrIntVector())
6045 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006046
6047 bool isSignBit = false;
6048
Dan Gohman81b28ce2008-09-16 18:46:06 +00006049 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006050 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006051 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006052
Chris Lattnerb6566012008-01-05 01:18:20 +00006053 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006055 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006056 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006057 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006058 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006059
Dan Gohman81b28ce2008-09-16 18:46:06 +00006060 // If we have an icmp le or icmp ge instruction, turn it into the
6061 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6062 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006063 switch (I.getPredicate()) {
6064 default: break;
6065 case ICmpInst::ICMP_ULE:
6066 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006067 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006068 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006069 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006070 case ICmpInst::ICMP_SLE:
6071 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006072 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006073 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006074 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006075 case ICmpInst::ICMP_UGE:
6076 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006077 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006079 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SGE:
6081 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006082 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006084 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006085 }
6086
Chris Lattner183661e2008-07-11 05:40:05 +00006087 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006088 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006089 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091 }
6092
6093 // See if we can fold the comparison based on range information we can get
6094 // by checking whether bits are known to be zero or one in the input.
6095 if (BitWidth != 0) {
6096 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006100 isSignBit ? APInt::getSignBit(BitWidth)
6101 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006103 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 if (SimplifyDemandedBits(I.getOperandUse(1),
6105 APInt::getAllOnesValue(BitWidth),
6106 Op1KnownZero, Op1KnownOne, 0))
6107 return &I;
6108
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006109 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006110 // in. Compute the Min, Max and RHS values based on the known bits. For the
6111 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116 Op0Min, Op0Max);
6117 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118 Op1Min, Op1Max);
6119 } else {
6120 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121 Op0Min, Op0Max);
6122 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123 Op1Min, Op1Max);
6124 }
6125
Chris Lattner183661e2008-07-11 05:40:05 +00006126 // If Min and Max are known to be the same, then SimplifyDemandedBits
6127 // figured out that the LHS is a constant. Just constant fold this now so
6128 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006130 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006131 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006133 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006134 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135
Chris Lattner183661e2008-07-11 05:40:05 +00006136 // Based on the range information we know about the LHS, see if we can
6137 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006138 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006139 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006140 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006142 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006143 break;
6144 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006147 break;
6148 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006150 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006152 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006154 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006158 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159
6160 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6161 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006163 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 }
Chris Lattner84dff672008-07-11 05:08:55 +00006165 break;
6166 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006168 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006170 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171
6172 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006177 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178
6179 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6180 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006181 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006182 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 }
Chris Lattner84dff672008-07-11 05:08:55 +00006184 break;
6185 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006187 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006189 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006194 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006195 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 }
Chris Lattner84dff672008-07-11 05:08:55 +00006197 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 case ICmpInst::ICMP_SGT:
6199 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006202 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203
6204 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006205 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006209 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 }
6211 break;
6212 case ICmpInst::ICMP_SGE:
6213 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006215 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006217 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 break;
6219 case ICmpInst::ICMP_SLE:
6220 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006222 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006224 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225 break;
6226 case ICmpInst::ICMP_UGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006229 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006230 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006231 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_ULE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006236 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006237 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006238 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006239 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006240 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241
6242 // Turn a signed comparison into an unsigned one if both operands
6243 // are known to have the same sign.
6244 if (I.isSignedPredicate() &&
6245 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006247 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006248 }
6249
6250 // Test if the ICmpInst instruction is used exclusively by a select as
6251 // part of a minimum or maximum operation. If so, refrain from doing
6252 // any other folding. This helps out other analyses which understand
6253 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254 // and CodeGen. And in this case, at least one of the comparison
6255 // operands has at least one user besides the compare (the select),
6256 // which would often largely negate the benefit of folding anyway.
6257 if (I.hasOneUse())
6258 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261 return 0;
6262
6263 // See if we are doing a comparison between a constant and an instruction that
6264 // can be folded into the comparison.
6265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006266 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006267 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006268 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006269 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006270 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006272 }
6273
Chris Lattner01deb9d2007-04-03 17:43:25 +00006274 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006275 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006278 case Instruction::GetElementPtr:
6279 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006281 bool isAllZeros = true;
6282 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283 if (!isa<Constant>(LHSI->getOperand(i)) ||
6284 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285 isAllZeros = false;
6286 break;
6287 }
6288 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006289 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006290 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 }
6292 break;
6293
Chris Lattner6970b662005-04-23 15:31:55 +00006294 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006295 // Only fold icmp into the PHI if the phi and fcmp are in the same
6296 // block. If in the same block, we're encouraging jump threading. If
6297 // not, we are just pessimizing the code by making an i1 phi.
6298 if (LHSI->getParent() == I.getParent())
6299 if (Instruction *NV = FoldOpIntoPhi(I))
6300 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006301 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006302 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006303 // If either operand of the select is a constant, we can fold the
6304 // comparison into the select arms, which will cause one to be
6305 // constant folded and the select turned into a bitwise or.
6306 Value *Op1 = 0, *Op2 = 0;
6307 if (LHSI->hasOneUse()) {
6308 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006310 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006311 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006312 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006313 LHSI->getOperand(2), RHSC,
6314 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006315 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006317 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006318 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006319 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006320 LHSI->getOperand(1), RHSC,
6321 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006322 }
6323 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006324
Chris Lattner6970b662005-04-23 15:31:55 +00006325 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006326 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006327 break;
6328 }
Chris Lattner4802d902007-04-06 18:57:34 +00006329 case Instruction::Malloc:
6330 // If we have (malloc != null), and if the malloc has a single use, we
6331 // can assume it is successful and remove the malloc.
6332 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333 AddToWorkList(LHSI);
Owen Andersoneed707b2009-07-24 23:12:02 +00006334 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006335 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006336 }
6337 break;
6338 }
Chris Lattner6970b662005-04-23 15:31:55 +00006339 }
6340
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006342 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006344 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006345 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006346 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006348 return NI;
6349
Reid Spencere4d87aa2006-12-23 06:05:41 +00006350 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006351 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6352 // now.
6353 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354 if (isa<PointerType>(Op0->getType()) &&
6355 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006356 // We keep moving the cast from the left operand over to the right
6357 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006358 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006359
Chris Lattner57d86372007-01-06 01:45:59 +00006360 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361 // so eliminate it as well.
6362 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006364
Chris Lattnerde90b762003-11-03 04:25:02 +00006365 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006366 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006367 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006368 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006369 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006370 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006371 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006372 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006373 }
Owen Anderson333c4002009-07-09 23:48:35 +00006374 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006375 }
Chris Lattner57d86372007-01-06 01:45:59 +00006376 }
6377
6378 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006379 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006380 // This comes up when you have code like
6381 // int X = A < B;
6382 // if (X) ...
6383 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006384 // with a constant or another cast from the same type.
6385 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006386 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006387 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006388 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006389
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006390 // See if it's the same type of instruction on the left and right.
6391 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006393 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006394 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006395 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006396 default: break;
6397 case Instruction::Add:
6398 case Instruction::Sub:
6399 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006400 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006401 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006402 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006403 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405 if (CI->getValue().isSignBit()) {
6406 ICmpInst::Predicate Pred = I.isSignedPredicate()
6407 ? I.getUnsignedPredicate()
6408 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006409 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006410 Op1I->getOperand(0));
6411 }
6412
6413 if (CI->getValue().isMaxSignedValue()) {
6414 ICmpInst::Predicate Pred = I.isSignedPredicate()
6415 ? I.getUnsignedPredicate()
6416 : I.getSignedPredicate();
6417 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006418 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006419 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006420 }
6421 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006422 break;
6423 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006424 if (!I.isEquality())
6425 break;
6426
Nick Lewycky5d52c452008-08-21 05:56:10 +00006427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429 // Mask = -1 >> count-trailing-zeros(Cst).
6430 if (!CI->isZero() && !CI->isOne()) {
6431 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006432 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006433 APInt::getLowBitsSet(AP.getBitWidth(),
6434 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006435 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006436 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437 Mask);
6438 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439 Mask);
6440 InsertNewInstBefore(And1, I);
6441 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006442 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006443 }
6444 }
6445 break;
6446 }
6447 }
6448 }
6449 }
6450
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006451 // ~x < ~y --> y < x
6452 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006453 if (match(Op0, m_Not(m_Value(A))) &&
6454 match(Op1, m_Not(m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006455 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006456 }
6457
Chris Lattner65b72ba2006-09-18 04:22:48 +00006458 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006459 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006460
6461 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006462 if (match(Op0, m_Neg(m_Value(A))) &&
6463 match(Op1, m_Neg(m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006464 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006465
Dan Gohman4ae51262009-08-12 16:23:25 +00006466 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006467 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6468 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006469 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006470 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006471 }
6472
Dan Gohman4ae51262009-08-12 16:23:25 +00006473 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006474 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006475 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006476 if (match(B, m_ConstantInt(C1)) &&
6477 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006478 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006479 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006480 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006481 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006482 InsertNewInstBefore(Xor, I));
6483 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484
6485 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006486 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006490 }
6491 }
6492
Dan Gohman4ae51262009-08-12 16:23:25 +00006493 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006494 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006495 // A == (A^B) -> B == 0
6496 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006497 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006498 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006499 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006500
6501 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006502 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006503 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006504 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006505
6506 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006507 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006508 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006509 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006510
Chris Lattner9c2328e2006-11-14 06:06:06 +00006511 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006513 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6514 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006515 Value *X = 0, *Y = 0, *Z = 0;
6516
6517 if (A == C) {
6518 X = B; Y = D; Z = A;
6519 } else if (A == D) {
6520 X = B; Y = C; Z = A;
6521 } else if (B == C) {
6522 X = A; Y = D; Z = B;
6523 } else if (B == D) {
6524 X = A; Y = C; Z = B;
6525 }
6526
6527 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006528 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006530 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006531 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006532 return &I;
6533 }
6534 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006535 }
Chris Lattner7e708292002-06-25 16:13:24 +00006536 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006537}
6538
Chris Lattner562ef782007-06-20 23:46:26 +00006539
6540/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541/// and CmpRHS are both known to be integer constants.
6542Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543 ConstantInt *DivRHS) {
6544 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545 const APInt &CmpRHSV = CmpRHS->getValue();
6546
6547 // FIXME: If the operand types don't match the type of the divide
6548 // then don't attempt this transform. The code below doesn't have the
6549 // logic to deal with a signed divide and an unsigned compare (and
6550 // vice versa). This is because (x /s C1) <s C2 produces different
6551 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552 // (x /u C1) <u C2. Simply casting the operands and result won't
6553 // work. :( The if statement below tests that condition and bails
6554 // if it finds it.
6555 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557 return 0;
6558 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006559 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006560 if (DivIsSigned && DivRHS->isAllOnesValue())
6561 return 0; // The overflow computation also screws up here
6562 if (DivRHS->isOne())
6563 return 0; // Not worth bothering, and eliminates some funny cases
6564 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006565
6566 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6568 // C2 (CI). By solving for X we can turn this into a range check
6569 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006570 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006571
6572 // Determine if the product overflows by seeing if the product is
6573 // not equal to the divide. Make sure we do the same kind of divide
6574 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006575 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6576 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006577
6578 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006579 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006580
Chris Lattner1dbfd482007-06-21 18:11:19 +00006581 // Figure out the interval that is being checked. For example, a comparison
6582 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6583 // Compute this interval based on the constants involved and the signedness of
6584 // the compare/divide. This computes a half-open interval, keeping track of
6585 // whether either value in the interval overflows. After analysis each
6586 // overflow variable is set to 0 if it's corresponding bound variable is valid
6587 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006589 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006590
Chris Lattner562ef782007-06-20 23:46:26 +00006591 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006592 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006593 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 HiOverflow = LoOverflow = ProdOV;
6595 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006596 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006597 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006598 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006599 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006600 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006601 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006602 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6604 HiOverflow = LoOverflow = ProdOV;
6605 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006606 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006607 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006609 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006610 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6611 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006612 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006613 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006615 true) ? -1 : 0;
6616 }
Chris Lattner562ef782007-06-20 23:46:26 +00006617 }
Dan Gohman76491272008-02-13 22:09:18 +00006618 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006619 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006620 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006621 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006622 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006623 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6624 HiOverflow = 1; // [INTMIN+1, overflow)
6625 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6626 }
Dan Gohman76491272008-02-13 22:09:18 +00006627 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006629 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006630 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006631 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006632 LoOverflow = AddWithOverflow(LoBound, HiBound,
6633 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006634 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006635 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6636 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006637 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006638 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006639 }
6640
Chris Lattner1dbfd482007-06-21 18:11:19 +00006641 // Dividing by a negative swaps the condition. LT <-> GT
6642 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006643 }
6644
6645 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006647 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006648 case ICmpInst::ICMP_EQ:
6649 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006650 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006651 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006652 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006653 ICmpInst::ICMP_UGE, X, LoBound);
6654 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006655 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006656 ICmpInst::ICMP_ULT, X, HiBound);
6657 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006658 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006659 case ICmpInst::ICMP_NE:
6660 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006661 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006662 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006663 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006664 ICmpInst::ICMP_ULT, X, LoBound);
6665 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006667 ICmpInst::ICMP_UGE, X, HiBound);
6668 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006670 case ICmpInst::ICMP_ULT:
6671 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006672 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006673 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006674 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006675 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Owen Anderson333c4002009-07-09 23:48:35 +00006676 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006677 case ICmpInst::ICMP_UGT:
6678 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006679 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006680 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006681 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006682 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006683 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006684 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006685 else
Owen Anderson333c4002009-07-09 23:48:35 +00006686 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006687 }
6688}
6689
6690
Chris Lattner01deb9d2007-04-03 17:43:25 +00006691/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6692///
6693Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6694 Instruction *LHSI,
6695 ConstantInt *RHS) {
6696 const APInt &RHSV = RHS->getValue();
6697
6698 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006699 case Instruction::Trunc:
6700 if (ICI.isEquality() && LHSI->hasOneUse()) {
6701 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6702 // of the high bits truncated out of x are known.
6703 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6704 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6705 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6706 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6707 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6708
6709 // If all the high bits are known, we can do this xform.
6710 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6711 // Pull in the high bits from known-ones set.
6712 APInt NewRHS(RHS->getValue());
6713 NewRHS.zext(SrcBits);
6714 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006715 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006716 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006717 }
6718 }
6719 break;
6720
Duncan Sands0091bf22007-04-04 06:42:45 +00006721 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006722 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6723 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6724 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006725 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6726 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006727 Value *CompareVal = LHSI->getOperand(0);
6728
6729 // If the sign bit of the XorCST is not set, there is no change to
6730 // the operation, just stop using the Xor.
6731 if (!XorCST->getValue().isNegative()) {
6732 ICI.setOperand(0, CompareVal);
6733 AddToWorkList(LHSI);
6734 return &ICI;
6735 }
6736
6737 // Was the old condition true if the operand is positive?
6738 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6739
6740 // If so, the new one isn't.
6741 isTrueIfPositive ^= true;
6742
6743 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006744 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006745 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006746 else
Owen Anderson333c4002009-07-09 23:48:35 +00006747 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006748 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006749 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006750
6751 if (LHSI->hasOneUse()) {
6752 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6753 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6754 const APInt &SignBit = XorCST->getValue();
6755 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6756 ? ICI.getUnsignedPredicate()
6757 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006758 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006759 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006760 }
6761
6762 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006763 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006764 const APInt &NotSignBit = XorCST->getValue();
6765 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6766 ? ICI.getUnsignedPredicate()
6767 : ICI.getSignedPredicate();
6768 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006769 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006770 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006771 }
6772 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 }
6774 break;
6775 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6776 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6777 LHSI->getOperand(0)->hasOneUse()) {
6778 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6779
6780 // If the LHS is an AND of a truncating cast, we can widen the
6781 // and/compare to be the input width without changing the value
6782 // produced, eliminating a cast.
6783 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6784 // We can do this transformation if either the AND constant does not
6785 // have its sign bit set or if it is an equality comparison.
6786 // Extending a relational comparison when we're checking the sign
6787 // bit would not work.
6788 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006789 (ICI.isEquality() ||
6790 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006791 uint32_t BitWidth =
6792 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6793 APInt NewCST = AndCST->getValue();
6794 NewCST.zext(BitWidth);
6795 APInt NewCI = RHSV;
6796 NewCI.zext(BitWidth);
6797 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006798 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006799 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006800 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006801 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006802 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006803 }
6804 }
6805
6806 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6807 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6808 // happens a LOT in code produced by the C front-end, for bitfield
6809 // access.
6810 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6811 if (Shift && !Shift->isShift())
6812 Shift = 0;
6813
6814 ConstantInt *ShAmt;
6815 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6816 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6817 const Type *AndTy = AndCST->getType(); // Type of the and.
6818
6819 // We can fold this as long as we can't shift unknown bits
6820 // into the mask. This can only happen with signed shift
6821 // rights, as they sign-extend.
6822 if (ShAmt) {
6823 bool CanFold = Shift->isLogicalShift();
6824 if (!CanFold) {
6825 // To test for the bad case of the signed shr, see if any
6826 // of the bits shifted in could be tested after the mask.
6827 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6828 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6829
6830 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6831 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6832 AndCST->getValue()) == 0)
6833 CanFold = true;
6834 }
6835
6836 if (CanFold) {
6837 Constant *NewCst;
6838 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006839 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006841 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006842
6843 // Check to see if we are shifting out any of the bits being
6844 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006845 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006846 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006847 // If we shifted bits out, the fold is not going to work out.
6848 // As a special case, check to see if this means that the
6849 // result is always true or false now.
6850 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006851 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006852 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006853 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 } else {
6855 ICI.setOperand(1, NewCst);
6856 Constant *NewAndCST;
6857 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006858 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006859 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006860 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006861 LHSI->setOperand(1, NewAndCST);
6862 LHSI->setOperand(0, Shift->getOperand(0));
6863 AddToWorkList(Shift); // Shift is dead.
6864 AddUsesToWorkList(ICI);
6865 return &ICI;
6866 }
6867 }
6868 }
6869
6870 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6871 // preferable because it allows the C<<Y expression to be hoisted out
6872 // of a loop if Y is invariant and X is not.
6873 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006874 ICI.isEquality() && !Shift->isArithmeticShift() &&
6875 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006876 // Compute C << Y.
6877 Value *NS;
6878 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006879 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006880 Shift->getOperand(1), "tmp");
6881 } else {
6882 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006883 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 Shift->getOperand(1), "tmp");
6885 }
6886 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6887
6888 // Compute X & (C << Y).
6889 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006890 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006891 InsertNewInstBefore(NewAnd, ICI);
6892
6893 ICI.setOperand(0, NewAnd);
6894 return &ICI;
6895 }
6896 }
6897 break;
6898
Chris Lattnera0141b92007-07-15 20:42:37 +00006899 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6900 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6901 if (!ShAmt) break;
6902
6903 uint32_t TypeBits = RHSV.getBitWidth();
6904
6905 // Check that the shift amount is in range. If not, don't perform
6906 // undefined shifts. When the shift is visited it will be
6907 // simplified.
6908 if (ShAmt->uge(TypeBits))
6909 break;
6910
6911 if (ICI.isEquality()) {
6912 // If we are comparing against bits always shifted out, the
6913 // comparison cannot succeed.
6914 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006915 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006916 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006917 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6918 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006919 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006920 return ReplaceInstUsesWith(ICI, Cst);
6921 }
6922
6923 if (LHSI->hasOneUse()) {
6924 // Otherwise strength reduce the shift into an and.
6925 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6926 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006927 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006928 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006929
Chris Lattnera0141b92007-07-15 20:42:37 +00006930 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006931 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006932 Mask, LHSI->getName()+".mask");
6933 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006934 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006935 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006936 }
6937 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006938
6939 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6940 bool TrueIfSigned = false;
6941 if (LHSI->hasOneUse() &&
6942 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6943 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006944 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006945 (TypeBits-ShAmt->getZExtValue()-1));
6946 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006947 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006948 Mask, LHSI->getName()+".mask");
6949 Value *And = InsertNewInstBefore(AndI, ICI);
6950
Owen Anderson333c4002009-07-09 23:48:35 +00006951 return new ICmpInst(*Context,
6952 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006953 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006954 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006955 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006956 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006957
6958 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006959 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006960 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006961 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006962 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006963
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006964 // Check that the shift amount is in range. If not, don't perform
6965 // undefined shifts. When the shift is visited it will be
6966 // simplified.
6967 uint32_t TypeBits = RHSV.getBitWidth();
6968 if (ShAmt->uge(TypeBits))
6969 break;
6970
6971 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006972
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006973 // If we are comparing against bits always shifted out, the
6974 // comparison cannot succeed.
6975 APInt Comp = RHSV << ShAmtVal;
6976 if (LHSI->getOpcode() == Instruction::LShr)
6977 Comp = Comp.lshr(ShAmtVal);
6978 else
6979 Comp = Comp.ashr(ShAmtVal);
6980
6981 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6982 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006983 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006984 return ReplaceInstUsesWith(ICI, Cst);
6985 }
6986
6987 // Otherwise, check to see if the bits shifted out are known to be zero.
6988 // If so, we can compare against the unshifted value:
6989 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006990 if (LHSI->hasOneUse() &&
6991 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006992 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006993 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006994 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006995 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006996
Evan Chengf30752c2008-04-23 00:38:06 +00006997 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006998 // Otherwise strength reduce the shift into an and.
6999 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007000 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007001
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007002 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007003 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007004 Mask, LHSI->getName()+".mask");
7005 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007006 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007007 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007008 }
7009 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007010 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007011
7012 case Instruction::SDiv:
7013 case Instruction::UDiv:
7014 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7015 // Fold this div into the comparison, producing a range check.
7016 // Determine, based on the divide type, what the range is being
7017 // checked. If there is an overflow on the low or high side, remember
7018 // it, otherwise compute the range [low, hi) bounding the new value.
7019 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007020 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7021 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7022 DivRHS))
7023 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007024 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007025
7026 case Instruction::Add:
7027 // Fold: icmp pred (add, X, C1), C2
7028
7029 if (!ICI.isEquality()) {
7030 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7031 if (!LHSC) break;
7032 const APInt &LHSV = LHSC->getValue();
7033
7034 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7035 .subtract(LHSV);
7036
7037 if (ICI.isSignedPredicate()) {
7038 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007039 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007040 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007041 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007042 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007043 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007044 }
7045 } else {
7046 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007047 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007048 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007049 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007050 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007051 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007052 }
7053 }
7054 }
7055 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007056 }
7057
7058 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7059 if (ICI.isEquality()) {
7060 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7061
7062 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7063 // the second operand is a constant, simplify a bit.
7064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7065 switch (BO->getOpcode()) {
7066 case Instruction::SRem:
7067 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7068 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7069 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7070 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7071 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007072 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007073 BO->getName());
7074 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007075 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007076 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 }
7078 }
7079 break;
7080 case Instruction::Add:
7081 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7082 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7083 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007084 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007085 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007086 } else if (RHSV == 0) {
7087 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7088 // efficiently invertible, or if the add has just this one use.
7089 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7090
Dan Gohman186a6362009-08-12 16:04:34 +00007091 if (Value *NegVal = dyn_castNegVal(BOp1))
Owen Anderson333c4002009-07-09 23:48:35 +00007092 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007093 else if (Value *NegVal = dyn_castNegVal(BOp0))
Owen Anderson333c4002009-07-09 23:48:35 +00007094 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 else if (BO->hasOneUse()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00007096 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 InsertNewInstBefore(Neg, ICI);
7098 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007099 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007100 }
7101 }
7102 break;
7103 case Instruction::Xor:
7104 // For the xor case, we can xor two constants together, eliminating
7105 // the explicit xor.
7106 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007107 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007108 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109
7110 // FALLTHROUGH
7111 case Instruction::Sub:
7112 // Replace (([sub|xor] A, B) != 0) with (A != B)
7113 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007114 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007115 BO->getOperand(1));
7116 break;
7117
7118 case Instruction::Or:
7119 // If bits are being or'd in that are not present in the constant we
7120 // are comparing against, then the comparison could never succeed!
7121 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007122 Constant *NotCI = ConstantExpr::getNot(RHS);
7123 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007124 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007125 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007126 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007127 }
7128 break;
7129
7130 case Instruction::And:
7131 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7132 // If bits are being compared against that are and'd out, then the
7133 // comparison can never succeed!
7134 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007135 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007136 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007137 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007138
7139 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7140 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007141 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007143 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007144
7145 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007146 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007148 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149 ICmpInst::Predicate pred = isICMP_NE ?
7150 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007151 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007152 }
7153
7154 // ((X & ~7) == 0) --> X < 8
7155 if (RHSV == 0 && isHighOnes(BOC)) {
7156 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007157 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 ICmpInst::Predicate pred = isICMP_NE ?
7159 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007160 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161 }
7162 }
7163 default: break;
7164 }
7165 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7166 // Handle icmp {eq|ne} <intrinsic>, intcst.
7167 if (II->getIntrinsicID() == Intrinsic::bswap) {
7168 AddToWorkList(II);
7169 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007170 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007171 return &ICI;
7172 }
7173 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007174 }
7175 return 0;
7176}
7177
7178/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7179/// We only handle extending casts so far.
7180///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7182 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007183 Value *LHSCIOp = LHSCI->getOperand(0);
7184 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007185 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007186 Value *RHSCIOp;
7187
Chris Lattner8c756c12007-05-05 22:41:33 +00007188 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7189 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007190 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7191 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007192 cast<IntegerType>(DestTy)->getBitWidth()) {
7193 Value *RHSOp = 0;
7194 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007195 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007196 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7197 RHSOp = RHSC->getOperand(0);
7198 // If the pointer types don't match, insert a bitcast.
7199 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007200 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007201 }
7202
7203 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007204 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007205 }
7206
7207 // The code below only handles extension cast instructions, so far.
7208 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007209 if (LHSCI->getOpcode() != Instruction::ZExt &&
7210 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007211 return 0;
7212
Reid Spencere4d87aa2006-12-23 06:05:41 +00007213 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7214 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007215
Reid Spencere4d87aa2006-12-23 06:05:41 +00007216 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007217 // Not an extension from the same type?
7218 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007219 if (RHSCIOp->getType() != LHSCIOp->getType())
7220 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007221
Nick Lewycky4189a532008-01-28 03:48:02 +00007222 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007223 // and the other is a zext), then we can't handle this.
7224 if (CI->getOpcode() != LHSCI->getOpcode())
7225 return 0;
7226
Nick Lewycky4189a532008-01-28 03:48:02 +00007227 // Deal with equality cases early.
7228 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007229 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007230
7231 // A signed comparison of sign extended values simplifies into a
7232 // signed comparison.
7233 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007234 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007235
7236 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007237 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007238 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007239
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 // If we aren't dealing with a constant on the RHS, exit early
7241 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7242 if (!CI)
7243 return 0;
7244
7245 // Compute the constant that would happen if we truncated to SrcTy then
7246 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007247 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7248 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007249 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007250
7251 // If the re-extended constant didn't change...
7252 if (Res2 == CI) {
7253 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7254 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007255 // %A = sext i16 %X to i32
7256 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007258 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 // because %A may have negative value.
7260 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007261 // However, we allow this when the compare is EQ/NE, because they are
7262 // signless.
7263 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007264 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007265 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 }
7267
7268 // The re-extended constant changed so the constant cannot be represented
7269 // in the shorter type. Consequently, we cannot emit a simple comparison.
7270
7271 // First, handle some easy cases. We know the result cannot be equal at this
7272 // point so handle the ICI.isEquality() cases
7273 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007274 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007276 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277
7278 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7279 // should have been folded away previously and not enter in here.
7280 Value *Result;
7281 if (isSignedCmp) {
7282 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007283 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007284 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007285 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007286 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 } else {
7288 // We're performing an unsigned comparison.
7289 if (isSignedExt) {
7290 // We're performing an unsigned comp with a sign extended value.
7291 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007292 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007293 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7294 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007295 } else {
7296 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007297 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007298 }
7299 }
7300
7301 // Finally, return the value computed.
7302 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007303 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007304 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007305
7306 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7307 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7308 "ICmp should be folded!");
7309 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007310 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007311 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007312}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007313
Reid Spencer832254e2007-02-02 02:16:23 +00007314Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7315 return commonShiftTransforms(I);
7316}
7317
7318Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7319 return commonShiftTransforms(I);
7320}
7321
7322Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007323 if (Instruction *R = commonShiftTransforms(I))
7324 return R;
7325
7326 Value *Op0 = I.getOperand(0);
7327
7328 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7329 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7330 if (CSI->isAllOnesValue())
7331 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007332
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007333 // See if we can turn a signed shr into an unsigned shr.
7334 if (MaskedValueIsZero(Op0,
7335 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7336 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7337
7338 // Arithmetic shifting an all-sign-bit value is a no-op.
7339 unsigned NumSignBits = ComputeNumSignBits(Op0);
7340 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7341 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007342
Chris Lattner348f6652007-12-06 01:59:46 +00007343 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007344}
7345
7346Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7347 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007349
7350 // shl X, 0 == X and shr X, 0 == X
7351 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007352 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7353 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007354 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007355
Reid Spencere4d87aa2006-12-23 06:05:41 +00007356 if (isa<UndefValue>(Op0)) {
7357 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007358 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007359 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007361 }
7362 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007363 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7364 return ReplaceInstUsesWith(I, Op0);
7365 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007367 }
7368
Dan Gohman9004c8a2009-05-21 02:28:33 +00007369 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007370 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007371 return &I;
7372
Chris Lattner2eefe512004-04-09 19:05:30 +00007373 // Try to fold constant and into select arguments.
7374 if (isa<Constant>(Op0))
7375 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007377 return R;
7378
Reid Spencerb83eb642006-10-20 07:07:24 +00007379 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007380 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7381 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007382 return 0;
7383}
7384
Reid Spencerb83eb642006-10-20 07:07:24 +00007385Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007386 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007387 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007388
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007389 // See if we can simplify any instructions used by the instruction whose sole
7390 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007391 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007392
Dan Gohmana119de82009-06-14 23:30:43 +00007393 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7394 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007395 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007396 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007397 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007398 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007399 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007400 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007401 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007402 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007403 }
7404
7405 // ((X*C1) << C2) == (X * (C1 << C2))
7406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7407 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7408 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007409 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007410 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007411
7412 // Try to fold constant and into select arguments.
7413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7415 return R;
7416 if (isa<PHINode>(Op0))
7417 if (Instruction *NV = FoldOpIntoPhi(I))
7418 return NV;
7419
Chris Lattner8999dd32007-12-22 09:07:47 +00007420 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7421 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7422 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7423 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7424 // place. Don't try to do this transformation in this case. Also, we
7425 // require that the input operand is a shift-by-constant so that we have
7426 // confidence that the shifts will get folded together. We could do this
7427 // xform in more cases, but it is unlikely to be profitable.
7428 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7429 isa<ConstantInt>(TrOp->getOperand(1))) {
7430 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007431 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007432 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007433 I.getName());
7434 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7435
7436 // For logical shifts, the truncation has the effect of making the high
7437 // part of the register be zeros. Emulate this by inserting an AND to
7438 // clear the top bits as needed. This 'and' will usually be zapped by
7439 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007440 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7441 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007442 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7443
7444 // The mask we constructed says what the trunc would do if occurring
7445 // between the shifts. We want to know the effect *after* the second
7446 // shift. We know that it is a logical shift by a constant, so adjust the
7447 // mask as appropriate.
7448 if (I.getOpcode() == Instruction::Shl)
7449 MaskV <<= Op1->getZExtValue();
7450 else {
7451 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7452 MaskV = MaskV.lshr(Op1->getZExtValue());
7453 }
7454
Owen Andersond672ecb2009-07-03 00:17:18 +00007455 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007456 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007457 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007458 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7459
7460 // Return the value truncated to the interesting size.
7461 return new TruncInst(And, I.getType());
7462 }
7463 }
7464
Chris Lattner4d5542c2006-01-06 07:12:35 +00007465 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007466 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7467 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7468 Value *V1, *V2;
7469 ConstantInt *CC;
7470 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007471 default: break;
7472 case Instruction::Add:
7473 case Instruction::And:
7474 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007475 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007476 // These operators commute.
7477 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007478 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007479 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007480 m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007481 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007482 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007483 Op0BO->getName());
7484 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007485 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007486 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007487 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007488 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007489 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007490 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007491 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007492 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007493
Chris Lattner150f12a2005-09-18 06:30:59 +00007494 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007495 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007496 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007497 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007498 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007499 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007500 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007501 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007502 Op0BO->getOperand(0), Op1,
7503 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007504 InsertNewInstBefore(YS, I); // (Y << C)
7505 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007506 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007507 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007508 V1->getName()+".mask");
7509 InsertNewInstBefore(XM, I); // X & (CC << C)
7510
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007511 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007512 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007513 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007514
Reid Spencera07cb7d2007-02-02 14:41:37 +00007515 // FALL THROUGH.
7516 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007517 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007518 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007519 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007520 m_Specific(Op1)))) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007521 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007522 Op0BO->getOperand(1), Op1,
7523 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007524 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007525 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007526 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007527 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007528 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007529 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007530 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007531 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007532 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007533
Chris Lattner13d4ab42006-05-31 21:14:00 +00007534 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7536 match(Op0BO->getOperand(0),
7537 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007538 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007539 cast<BinaryOperator>(Op0BO->getOperand(0))
7540 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007541 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007542 Op0BO->getOperand(1), Op1,
7543 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007544 InsertNewInstBefore(YS, I); // (Y << C)
7545 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007546 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007547 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007548 V1->getName()+".mask");
7549 InsertNewInstBefore(XM, I); // X & (CC << C)
7550
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007551 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007552 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007553
Chris Lattner11021cb2005-09-18 05:12:10 +00007554 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007555 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007556 }
7557
7558
7559 // If the operand is an bitwise operator with a constant RHS, and the
7560 // shift is the only use, we can pull it out of the shift.
7561 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7562 bool isValid = true; // Valid only for And, Or, Xor
7563 bool highBitSet = false; // Transform if high bit of constant set?
7564
7565 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007566 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007567 case Instruction::Add:
7568 isValid = isLeftShift;
7569 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007570 case Instruction::Or:
7571 case Instruction::Xor:
7572 highBitSet = false;
7573 break;
7574 case Instruction::And:
7575 highBitSet = true;
7576 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007577 }
7578
7579 // If this is a signed shift right, and the high bit is modified
7580 // by the logical operation, do not perform the transformation.
7581 // The highBitSet boolean indicates the value of the high bit of
7582 // the constant which would cause it to be modified for this
7583 // operation.
7584 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007585 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007586 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007587
7588 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007589 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007590
7591 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007592 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007593 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007594 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007595
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007596 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007597 NewRHS);
7598 }
7599 }
7600 }
7601 }
7602
Chris Lattnerad0124c2006-01-06 07:52:12 +00007603 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007604 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7605 if (ShiftOp && !ShiftOp->isShift())
7606 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007607
Reid Spencerb83eb642006-10-20 07:07:24 +00007608 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007609 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007610 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7611 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007612 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7613 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7614 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007615
Zhou Sheng4351c642007-04-02 08:20:41 +00007616 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007617
7618 const IntegerType *Ty = cast<IntegerType>(I.getType());
7619
7620 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007621 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007622 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7623 // saturates.
7624 if (AmtSum >= TypeBits) {
7625 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007626 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007627 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7628 }
7629
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007630 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007631 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7633 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007634 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007635 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007636
Chris Lattnerb87056f2007-02-05 00:57:54 +00007637 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007638 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007639 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7640 I.getOpcode() == Instruction::LShr) {
7641 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007642 if (AmtSum >= TypeBits)
7643 AmtSum = TypeBits-1;
7644
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007646 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 InsertNewInstBefore(Shift, I);
7648
Zhou Shenge9e03f62007-03-28 15:02:20 +00007649 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007650 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007651 }
7652
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 // Okay, if we get here, one shift must be left, and the other shift must be
7654 // right. See if the amounts are equal.
7655 if (ShiftAmt1 == ShiftAmt2) {
7656 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7657 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007658 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007659 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007660 }
7661 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7662 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007663 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007664 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007665 }
7666 // We can simplify ((X << C) >>s C) into a trunc + sext.
7667 // NOTE: we could do this for any C, but that would make 'unusual' integer
7668 // types. For now, just stick to ones well-supported by the code
7669 // generators.
7670 const Type *SExtType = 0;
7671 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007672 case 1 :
7673 case 8 :
7674 case 16 :
7675 case 32 :
7676 case 64 :
7677 case 128:
Owen Andersondebcb012009-07-29 22:17:13 +00007678 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007679 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007680 default: break;
7681 }
7682 if (SExtType) {
7683 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7684 InsertNewInstBefore(NewTrunc, I);
7685 return new SExtInst(NewTrunc, Ty);
7686 }
7687 // Otherwise, we can't handle it yet.
7688 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007689 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007690
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007691 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007692 if (I.getOpcode() == Instruction::Shl) {
7693 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7694 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007695 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007696 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007697 InsertNewInstBefore(Shift, I);
7698
Reid Spencer55702aa2007-03-25 21:11:44 +00007699 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007700 return BinaryOperator::CreateAnd(Shift,
7701 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007702 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007704 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007705 if (I.getOpcode() == Instruction::LShr) {
7706 assert(ShiftOp->getOpcode() == Instruction::Shl);
7707 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007708 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007709 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007710
Reid Spencerd5e30f02007-03-26 17:18:58 +00007711 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007712 return BinaryOperator::CreateAnd(Shift,
7713 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007714 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715
7716 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7717 } else {
7718 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007719 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007721 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722 if (I.getOpcode() == Instruction::Shl) {
7723 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7724 ShiftOp->getOpcode() == Instruction::AShr);
7725 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007726 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007727 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007728 InsertNewInstBefore(Shift, I);
7729
Reid Spencer55702aa2007-03-25 21:11:44 +00007730 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007731 return BinaryOperator::CreateAnd(Shift,
7732 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007733 }
7734
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007735 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007736 if (I.getOpcode() == Instruction::LShr) {
7737 assert(ShiftOp->getOpcode() == Instruction::Shl);
7738 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007739 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007740 InsertNewInstBefore(Shift, I);
7741
Reid Spencer68d27cf2007-03-26 23:45:51 +00007742 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007743 return BinaryOperator::CreateAnd(Shift,
7744 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007745 }
7746
7747 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007748 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007749 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007750 return 0;
7751}
7752
Chris Lattnera1be5662002-05-02 17:06:02 +00007753
Chris Lattnercfd65102005-10-29 04:36:15 +00007754/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7755/// expression. If so, decompose it, returning some value X, such that Val is
7756/// X*Scale+Offset.
7757///
7758static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007759 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007760 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007761 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007762 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007763 Scale = 0;
Owen Andersoneed707b2009-07-24 23:12:02 +00007764 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007765 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7766 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7767 if (I->getOpcode() == Instruction::Shl) {
7768 // This is a value scaled by '1 << the shift amt'.
7769 Scale = 1U << RHS->getZExtValue();
7770 Offset = 0;
7771 return I->getOperand(0);
7772 } else if (I->getOpcode() == Instruction::Mul) {
7773 // This value is scaled by 'RHS'.
7774 Scale = RHS->getZExtValue();
7775 Offset = 0;
7776 return I->getOperand(0);
7777 } else if (I->getOpcode() == Instruction::Add) {
7778 // We have X+C. Check to see if we really have (X*C2)+C1,
7779 // where C1 is divisible by C2.
7780 unsigned SubScale;
7781 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007782 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7783 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007784 Offset += RHS->getZExtValue();
7785 Scale = SubScale;
7786 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007787 }
7788 }
7789 }
7790
7791 // Otherwise, we can't look past this.
7792 Scale = 1;
7793 Offset = 0;
7794 return Val;
7795}
7796
7797
Chris Lattnerb3f83972005-10-24 06:03:58 +00007798/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7799/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007800Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007801 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007802 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007803
Chris Lattnerb53c2382005-10-24 06:22:12 +00007804 // Remove any uses of AI that are dead.
7805 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007806
Chris Lattnerb53c2382005-10-24 06:22:12 +00007807 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7808 Instruction *User = cast<Instruction>(*UI++);
7809 if (isInstructionTriviallyDead(User)) {
7810 while (UI != E && *UI == User)
7811 ++UI; // If this instruction uses AI more than once, don't break UI.
7812
Chris Lattnerb53c2382005-10-24 06:22:12 +00007813 ++NumDeadInst;
Dan Gohman2df6e642009-08-12 16:28:31 +00007814 DOUT << "IC: DCE: " << *User << '\n';
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007815 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007816 }
7817 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007818
7819 // This requires TargetData to get the alloca alignment and size information.
7820 if (!TD) return 0;
7821
Chris Lattnerb3f83972005-10-24 06:03:58 +00007822 // Get the type really allocated and the type casted to.
7823 const Type *AllocElTy = AI.getAllocatedType();
7824 const Type *CastElTy = PTy->getElementType();
7825 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007826
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007827 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7828 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007829 if (CastElTyAlign < AllocElTyAlign) return 0;
7830
Chris Lattner39387a52005-10-24 06:35:18 +00007831 // If the allocation has multiple uses, only promote it if we are strictly
7832 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007833 // same, we open the door to infinite loops of various kinds. (A reference
7834 // from a dbg.declare doesn't count as a use for this purpose.)
7835 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7836 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007837
Duncan Sands777d2302009-05-09 07:06:46 +00007838 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7839 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007840 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007841
Chris Lattner455fcc82005-10-29 03:19:53 +00007842 // See if we can satisfy the modulus by pulling a scale out of the array
7843 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007844 unsigned ArraySizeScale;
7845 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007846 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007847 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7848 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007849
Chris Lattner455fcc82005-10-29 03:19:53 +00007850 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7851 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007852 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7853 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007854
Chris Lattner455fcc82005-10-29 03:19:53 +00007855 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7856 Value *Amt = 0;
7857 if (Scale == 1) {
7858 Amt = NumElements;
7859 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007860 // If the allocation size is constant, form a constant mul expression
Owen Andersoneed707b2009-07-24 23:12:02 +00007861 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007862 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007863 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007864 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007865 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007866 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007867 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007868 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007869 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007870 }
7871
Jeff Cohen86796be2007-04-04 16:58:57 +00007872 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007873 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007874 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007875 Amt = InsertNewInstBefore(Tmp, AI);
7876 }
7877
Chris Lattnerb3f83972005-10-24 06:03:58 +00007878 AllocationInst *New;
7879 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007880 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007881 else
Owen Anderson50dead02009-07-15 23:53:25 +00007882 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007883 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007884 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007885
Dale Johannesena0a66372009-03-05 00:39:02 +00007886 // If the allocation has one real use plus a dbg.declare, just remove the
7887 // declare.
7888 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7889 EraseInstFromFunction(*DI);
7890 }
7891 // If the allocation has multiple real uses, insert a cast and change all
7892 // things that used it to use the new cast. This will also hack on CI, but it
7893 // will die soon.
7894 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007895 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007896 // New is the allocation instruction, pointer typed. AI is the original
7897 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7898 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007899 InsertNewInstBefore(NewCast, AI);
7900 AI.replaceAllUsesWith(NewCast);
7901 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007902 return ReplaceInstUsesWith(CI, New);
7903}
7904
Chris Lattner70074e02006-05-13 02:06:03 +00007905/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007906/// and return it as type Ty without inserting any new casts and without
7907/// changing the computed value. This is used by code that tries to decide
7908/// whether promoting or shrinking integer operations to wider or smaller types
7909/// will allow us to eliminate a truncate or extend.
7910///
7911/// This is a truncation operation if Ty is smaller than V->getType(), or an
7912/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007913///
7914/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7915/// should return true if trunc(V) can be computed by computing V in the smaller
7916/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7917/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7918/// efficiently truncated.
7919///
7920/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7921/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7922/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007923bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007924 unsigned CastOpc,
7925 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007926 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007927 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007929
7930 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007931 if (!I) return false;
7932
Dan Gohman6de29f82009-06-15 22:12:54 +00007933 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007934
Chris Lattner951626b2007-08-02 06:11:14 +00007935 // If this is an extension or truncate, we can often eliminate it.
7936 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7937 // If this is a cast from the destination type, we can trivially eliminate
7938 // it, and this will remove a cast overall.
7939 if (I->getOperand(0)->getType() == Ty) {
7940 // If the first operand is itself a cast, and is eliminable, do not count
7941 // this as an eliminable cast. We would prefer to eliminate those two
7942 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007943 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007944 ++NumCastsRemoved;
7945 return true;
7946 }
7947 }
7948
7949 // We can't extend or shrink something that has multiple uses: doing so would
7950 // require duplicating the instruction in general, which isn't profitable.
7951 if (!I->hasOneUse()) return false;
7952
Evan Chengf35fd542009-01-15 17:01:23 +00007953 unsigned Opc = I->getOpcode();
7954 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007955 case Instruction::Add:
7956 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007957 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007958 case Instruction::And:
7959 case Instruction::Or:
7960 case Instruction::Xor:
7961 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007962 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007963 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007964 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007965 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007966
Eli Friedman070a9812009-07-13 22:46:01 +00007967 case Instruction::UDiv:
7968 case Instruction::URem: {
7969 // UDiv and URem can be truncated if all the truncated bits are zero.
7970 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7971 uint32_t BitWidth = Ty->getScalarSizeInBits();
7972 if (BitWidth < OrigBitWidth) {
7973 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7974 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7975 MaskedValueIsZero(I->getOperand(1), Mask)) {
7976 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7977 NumCastsRemoved) &&
7978 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7979 NumCastsRemoved);
7980 }
7981 }
7982 break;
7983 }
Chris Lattner46b96052006-11-29 07:18:39 +00007984 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007985 // If we are truncating the result of this SHL, and if it's a shift of a
7986 // constant amount, we can always perform a SHL in a smaller type.
7987 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007988 uint32_t BitWidth = Ty->getScalarSizeInBits();
7989 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007990 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007991 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007992 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007993 }
7994 break;
7995 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007996 // If this is a truncate of a logical shr, we can truncate it to a smaller
7997 // lshr iff we know that the bits we would otherwise be shifting in are
7998 // already zeros.
7999 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008000 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8001 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008002 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008003 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008004 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8005 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008006 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008007 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008008 }
8009 }
Chris Lattner46b96052006-11-29 07:18:39 +00008010 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008011 case Instruction::ZExt:
8012 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008013 case Instruction::Trunc:
8014 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008015 // can safely replace it. Note that replacing it does not reduce the number
8016 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008017 if (Opc == CastOpc)
8018 return true;
8019
8020 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008021 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008022 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008023 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008024 case Instruction::Select: {
8025 SelectInst *SI = cast<SelectInst>(I);
8026 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008027 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008028 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008029 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008030 }
Chris Lattner8114b712008-06-18 04:00:49 +00008031 case Instruction::PHI: {
8032 // We can change a phi if we can change all operands.
8033 PHINode *PN = cast<PHINode>(I);
8034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8035 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008036 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008037 return false;
8038 return true;
8039 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008040 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008041 // TODO: Can handle more cases here.
8042 break;
8043 }
8044
8045 return false;
8046}
8047
8048/// EvaluateInDifferentType - Given an expression that
8049/// CanEvaluateInDifferentType returns true for, actually insert the code to
8050/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008051Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008052 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008053 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008054 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008055 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008056
8057 // Otherwise, it must be an instruction.
8058 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008059 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008060 unsigned Opc = I->getOpcode();
8061 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008062 case Instruction::Add:
8063 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008064 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008065 case Instruction::And:
8066 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008067 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008068 case Instruction::AShr:
8069 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008070 case Instruction::Shl:
8071 case Instruction::UDiv:
8072 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008073 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008075 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008076 break;
8077 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008078 case Instruction::Trunc:
8079 case Instruction::ZExt:
8080 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008081 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008082 // just return the source. There's no need to insert it because it is not
8083 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008084 if (I->getOperand(0)->getType() == Ty)
8085 return I->getOperand(0);
8086
Chris Lattner8114b712008-06-18 04:00:49 +00008087 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008088 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008089 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008090 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008091 case Instruction::Select: {
8092 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8093 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8094 Res = SelectInst::Create(I->getOperand(0), True, False);
8095 break;
8096 }
Chris Lattner8114b712008-06-18 04:00:49 +00008097 case Instruction::PHI: {
8098 PHINode *OPN = cast<PHINode>(I);
8099 PHINode *NPN = PHINode::Create(Ty);
8100 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8101 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8102 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8103 }
8104 Res = NPN;
8105 break;
8106 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008108 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008109 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008110 break;
8111 }
8112
Chris Lattner8114b712008-06-18 04:00:49 +00008113 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008114 return InsertNewInstBefore(Res, *I);
8115}
8116
Reid Spencer3da59db2006-11-27 01:05:10 +00008117/// @brief Implement the transforms common to all CastInst visitors.
8118Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008119 Value *Src = CI.getOperand(0);
8120
Dan Gohman23d9d272007-05-11 21:10:54 +00008121 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008122 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008123 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008124 if (Instruction::CastOps opc =
8125 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8126 // The first cast (CSrc) is eliminable so we need to fix up or replace
8127 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008128 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008129 }
8130 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008131
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008133 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8134 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8135 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008136
8137 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008138 if (isa<PHINode>(Src))
8139 if (Instruction *NV = FoldOpIntoPhi(CI))
8140 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008141
Reid Spencer3da59db2006-11-27 01:05:10 +00008142 return 0;
8143}
8144
Chris Lattner46cd5a12009-01-09 05:44:56 +00008145/// FindElementAtOffset - Given a type and a constant offset, determine whether
8146/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008147/// the specified offset. If so, fill them into NewIndices and return the
8148/// resultant element type, otherwise return null.
8149static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8150 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008151 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008152 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008153 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008154 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008155
8156 // Start with the index over the outer type. Note that the type size
8157 // might be zero (even if the offset isn't zero) if the indexed type
8158 // is something like [0 x {int, int}]
8159 const Type *IntPtrTy = TD->getIntPtrType();
8160 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008161 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008162 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008163 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008164
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008165 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008166 if (Offset < 0) {
8167 --FirstIdx;
8168 Offset += TySize;
8169 assert(Offset >= 0);
8170 }
8171 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8172 }
8173
Owen Andersoneed707b2009-07-24 23:12:02 +00008174 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008175
8176 // Index into the types. If we fail, set OrigBase to null.
8177 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008178 // Indexing into tail padding between struct/array elements.
8179 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008180 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008181
Chris Lattner46cd5a12009-01-09 05:44:56 +00008182 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8183 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008184 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8185 "Offset must stay within the indexed type");
8186
Chris Lattner46cd5a12009-01-09 05:44:56 +00008187 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneed707b2009-07-24 23:12:02 +00008188 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008189
8190 Offset -= SL->getElementOffset(Elt);
8191 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008192 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008193 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008194 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008195 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008196 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008197 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008198 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008199 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008200 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008201 }
8202 }
8203
Chris Lattner3914f722009-01-24 01:00:13 +00008204 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008205}
8206
Chris Lattnerd3e28342007-04-27 17:44:50 +00008207/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8208Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8209 Value *Src = CI.getOperand(0);
8210
Chris Lattnerd3e28342007-04-27 17:44:50 +00008211 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008212 // If casting the result of a getelementptr instruction with no offset, turn
8213 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008214 if (GEP->hasAllZeroIndices()) {
8215 // Changing the cast operand is usually not a good idea but it is safe
8216 // here because the pointer operand is being replaced with another
8217 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008218 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008219 CI.setOperand(0, GEP->getOperand(0));
8220 return &CI;
8221 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008222
8223 // If the GEP has a single use, and the base pointer is a bitcast, and the
8224 // GEP computes a constant offset, see if we can convert these three
8225 // instructions into fewer. This typically happens with unions and other
8226 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008227 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008228 if (GEP->hasAllConstantIndices()) {
8229 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008230 ConstantInt *OffsetV =
8231 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008232 int64_t Offset = OffsetV->getSExtValue();
8233
8234 // Get the base pointer input of the bitcast, and the type it points to.
8235 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8236 const Type *GEPIdxTy =
8237 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008238 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008239 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008240 // If we were able to index down into an element, create the GEP
8241 // and bitcast the result. This eliminates one bitcast, potentially
8242 // two.
8243 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8244 NewIndices.begin(),
8245 NewIndices.end(), "");
8246 InsertNewInstBefore(NGEP, CI);
8247 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008248 if (cast<GEPOperator>(GEP)->isInBounds())
8249 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008250
Chris Lattner46cd5a12009-01-09 05:44:56 +00008251 if (isa<BitCastInst>(CI))
8252 return new BitCastInst(NGEP, CI.getType());
8253 assert(isa<PtrToIntInst>(CI));
8254 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008255 }
8256 }
8257 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008258 }
8259
8260 return commonCastTransforms(CI);
8261}
8262
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008263/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8264/// type like i42. We don't want to introduce operations on random non-legal
8265/// integer types where they don't already exist in the code. In the future,
8266/// we should consider making this based off target-data, so that 32-bit targets
8267/// won't get i64 operations etc.
8268static bool isSafeIntegerType(const Type *Ty) {
8269 switch (Ty->getPrimitiveSizeInBits()) {
8270 case 8:
8271 case 16:
8272 case 32:
8273 case 64:
8274 return true;
8275 default:
8276 return false;
8277 }
8278}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008279
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008280/// commonIntCastTransforms - This function implements the common transforms
8281/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008282Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8283 if (Instruction *Result = commonCastTransforms(CI))
8284 return Result;
8285
8286 Value *Src = CI.getOperand(0);
8287 const Type *SrcTy = Src->getType();
8288 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008289 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8290 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008291
Reid Spencer3da59db2006-11-27 01:05:10 +00008292 // See if we can simplify any instructions used by the LHS whose sole
8293 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008294 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 return &CI;
8296
8297 // If the source isn't an instruction or has more than one use then we
8298 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008299 Instruction *SrcI = dyn_cast<Instruction>(Src);
8300 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008301 return 0;
8302
Chris Lattnerc739cd62007-03-03 05:27:34 +00008303 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008305 // Only do this if the dest type is a simple type, don't convert the
8306 // expression tree to something weird like i93 unless the source is also
8307 // strange.
8308 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008309 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8310 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008311 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008313 // eliminates the cast, so it is always a win. If this is a zero-extension,
8314 // we need to do an AND to maintain the clear top-part of the computation,
8315 // so we require that the input have eliminated at least one cast. If this
8316 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008317 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008318 bool DoXForm = false;
8319 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008320 switch (CI.getOpcode()) {
8321 default:
8322 // All the others use floating point so we shouldn't actually
8323 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008324 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008325 case Instruction::Trunc:
8326 DoXForm = true;
8327 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008329 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008330 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 // If it's unnecessary to issue an AND to clear the high bits, it's
8332 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008333 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008334 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8335 if (MaskedValueIsZero(TryRes, Mask))
8336 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008337
8338 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008339 if (TryI->use_empty())
8340 EraseInstFromFunction(*TryI);
8341 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008342 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008343 }
Evan Chengf35fd542009-01-15 17:01:23 +00008344 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008345 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008346 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008347 // If we do not have to emit the truncate + sext pair, then it's always
8348 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008349 //
8350 // It's not safe to eliminate the trunc + sext pair if one of the
8351 // eliminated cast is a truncate. e.g.
8352 // t2 = trunc i32 t1 to i16
8353 // t3 = sext i16 t2 to i32
8354 // !=
8355 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008356 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8358 if (NumSignBits > (DestBitSize - SrcBitSize))
8359 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008360
8361 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362 if (TryI->use_empty())
8363 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008364 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008365 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 }
Evan Chengf35fd542009-01-15 17:01:23 +00008367 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008368
8369 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008370 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8371 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008372 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8373 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008375 // Just replace this cast with the result.
8376 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008377
Reid Spencer3da59db2006-11-27 01:05:10 +00008378 assert(Res->getType() == DestTy);
8379 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008380 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 // Just replace this cast with the result.
8383 return ReplaceInstUsesWith(CI, Res);
8384 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386
8387 // If the high bits are already zero, just replace this cast with the
8388 // result.
8389 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8390 if (MaskedValueIsZero(Res, Mask))
8391 return ReplaceInstUsesWith(CI, Res);
8392
8393 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008394 Constant *C = ConstantInt::get(*Context,
8395 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008396 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008398 case Instruction::SExt: {
8399 // If the high bits are already filled with sign bit, just replace this
8400 // cast with the result.
8401 unsigned NumSignBits = ComputeNumSignBits(Res);
8402 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008403 return ReplaceInstUsesWith(CI, Res);
8404
Reid Spencer3da59db2006-11-27 01:05:10 +00008405 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008406 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008407 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8408 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008409 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008410 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008411 }
8412 }
8413
8414 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8415 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8416
8417 switch (SrcI->getOpcode()) {
8418 case Instruction::Add:
8419 case Instruction::Mul:
8420 case Instruction::And:
8421 case Instruction::Or:
8422 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008423 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008424 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8425 // Don't insert two casts unless at least one can be eliminated.
8426 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008427 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008428 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8429 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008430 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008431 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008432 }
8433 }
8434
8435 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8436 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8437 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008438 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008439 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008440 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008441 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008442 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008443 }
8444 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008445
Eli Friedman65445c52009-07-13 21:45:57 +00008446 case Instruction::Shl: {
8447 // Canonicalize trunc inside shl, if we can.
8448 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8449 if (CI && DestBitSize < SrcBitSize &&
8450 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8451 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8452 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008453 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008454 }
8455 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008456 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008457 }
8458 return 0;
8459}
8460
Chris Lattner8a9f5712007-04-11 06:57:46 +00008461Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008462 if (Instruction *Result = commonIntCastTransforms(CI))
8463 return Result;
8464
8465 Value *Src = CI.getOperand(0);
8466 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008467 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8468 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008469
8470 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008471 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008472 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008473 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008474 Value *Zero = Constant::getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008475 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008476 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008477
Chris Lattner4f9797d2009-03-24 18:15:30 +00008478 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8479 ConstantInt *ShAmtV = 0;
8480 Value *ShiftOp = 0;
8481 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008482 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008483 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8484
8485 // Get a mask for the bits shifting in.
8486 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8487 if (MaskedValueIsZero(ShiftOp, Mask)) {
8488 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008489 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008490
8491 // Okay, we can shrink this. Truncate the input, then return a new
8492 // shift.
8493 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008494 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008495 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008496 }
8497 }
8498
8499 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008500}
8501
Evan Chengb98a10e2008-03-24 00:21:34 +00008502/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8503/// in order to eliminate the icmp.
8504Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8505 bool DoXform) {
8506 // If we are just checking for a icmp eq of a single bit and zext'ing it
8507 // to an integer, then shift the bit to the appropriate place and then
8508 // cast to integer to avoid the comparison.
8509 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8510 const APInt &Op1CV = Op1C->getValue();
8511
8512 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8513 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8514 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8515 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8516 if (!DoXform) return ICI;
8517
8518 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008519 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008520 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008521 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008522 In->getName()+".lobit"),
8523 CI);
8524 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008525 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008526 false/*ZExt*/, "tmp", &CI);
8527
8528 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008529 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008530 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008531 In->getName()+".not"),
8532 CI);
8533 }
8534
8535 return ReplaceInstUsesWith(CI, In);
8536 }
8537
8538
8539
8540 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8541 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8542 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8543 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8544 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8545 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8546 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8547 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8548 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8549 // This only works for EQ and NE
8550 ICI->isEquality()) {
8551 // If Op1C some other power of two, convert:
8552 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8553 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8554 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8555 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8556
8557 APInt KnownZeroMask(~KnownZero);
8558 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8559 if (!DoXform) return ICI;
8560
8561 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8562 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8563 // (X&4) == 2 --> false
8564 // (X&4) != 2 --> true
Owen Andersoneed707b2009-07-24 23:12:02 +00008565 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008566 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008567 return ReplaceInstUsesWith(CI, Res);
8568 }
8569
8570 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8571 Value *In = ICI->getOperand(0);
8572 if (ShiftAmt) {
8573 // Perform a logical shr by shiftamt.
8574 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008575 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008576 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008577 In->getName()+".lobit"), CI);
8578 }
8579
8580 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008581 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008582 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008583 InsertNewInstBefore(cast<Instruction>(In), CI);
8584 }
8585
8586 if (CI.getType() == In->getType())
8587 return ReplaceInstUsesWith(CI, In);
8588 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008589 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008590 }
8591 }
8592 }
8593
8594 return 0;
8595}
8596
Chris Lattner8a9f5712007-04-11 06:57:46 +00008597Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008598 // If one of the common conversion will work ..
8599 if (Instruction *Result = commonIntCastTransforms(CI))
8600 return Result;
8601
8602 Value *Src = CI.getOperand(0);
8603
Chris Lattnera84f47c2009-02-17 20:47:23 +00008604 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8605 // types and if the sizes are just right we can convert this into a logical
8606 // 'and' which will be much cheaper than the pair of casts.
8607 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8608 // Get the sizes of the types involved. We know that the intermediate type
8609 // will be smaller than A or C, but don't know the relation between A and C.
8610 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008611 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8612 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8613 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008614 // If we're actually extending zero bits, then if
8615 // SrcSize < DstSize: zext(a & mask)
8616 // SrcSize == DstSize: a & mask
8617 // SrcSize > DstSize: trunc(a) & mask
8618 if (SrcSize < DstSize) {
8619 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008620 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008621 Instruction *And =
8622 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8623 InsertNewInstBefore(And, CI);
8624 return new ZExtInst(And, CI.getType());
8625 } else if (SrcSize == DstSize) {
8626 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008627 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008628 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008629 } else if (SrcSize > DstSize) {
8630 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8631 InsertNewInstBefore(Trunc, CI);
8632 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008633 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008634 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008635 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008636 }
8637 }
8638
Evan Chengb98a10e2008-03-24 00:21:34 +00008639 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8640 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008641
Evan Chengb98a10e2008-03-24 00:21:34 +00008642 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8643 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8644 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8645 // of the (zext icmp) will be transformed.
8646 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8647 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8648 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8649 (transformZExtICmp(LHS, CI, false) ||
8650 transformZExtICmp(RHS, CI, false))) {
8651 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8652 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008653 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008654 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008655 }
8656
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008657 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008658 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8659 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8660 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8661 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008662 if (TI0->getType() == CI.getType())
8663 return
8664 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008665 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008666 }
8667
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008668 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8669 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8670 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8671 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8672 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8673 And->getOperand(1) == C)
8674 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8675 Value *TI0 = TI->getOperand(0);
8676 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008677 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008678 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8679 InsertNewInstBefore(NewAnd, *And);
8680 return BinaryOperator::CreateXor(NewAnd, ZC);
8681 }
8682 }
8683
Reid Spencer3da59db2006-11-27 01:05:10 +00008684 return 0;
8685}
8686
Chris Lattner8a9f5712007-04-11 06:57:46 +00008687Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008688 if (Instruction *I = commonIntCastTransforms(CI))
8689 return I;
8690
Chris Lattner8a9f5712007-04-11 06:57:46 +00008691 Value *Src = CI.getOperand(0);
8692
Dan Gohman1975d032008-10-30 20:40:10 +00008693 // Canonicalize sign-extend from i1 to a select.
8694 if (Src->getType() == Type::Int1Ty)
8695 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008696 Constant::getAllOnesValue(CI.getType()),
8697 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008698
8699 // See if the value being truncated is already sign extended. If so, just
8700 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008701 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008702 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008703 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8704 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8705 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008706 unsigned NumSignBits = ComputeNumSignBits(Op);
8707
8708 if (OpBits == DestBits) {
8709 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8710 // bits, it is already ready.
8711 if (NumSignBits > DestBits-MidBits)
8712 return ReplaceInstUsesWith(CI, Op);
8713 } else if (OpBits < DestBits) {
8714 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8715 // bits, just sext from i32.
8716 if (NumSignBits > OpBits-MidBits)
8717 return new SExtInst(Op, CI.getType(), "tmp");
8718 } else {
8719 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8720 // bits, just truncate to i32.
8721 if (NumSignBits > OpBits-MidBits)
8722 return new TruncInst(Op, CI.getType(), "tmp");
8723 }
8724 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008725
8726 // If the input is a shl/ashr pair of a same constant, then this is a sign
8727 // extension from a smaller value. If we could trust arbitrary bitwidth
8728 // integers, we could turn this into a truncate to the smaller bit and then
8729 // use a sext for the whole extension. Since we don't, look deeper and check
8730 // for a truncate. If the source and dest are the same type, eliminate the
8731 // trunc and extend and just do shifts. For example, turn:
8732 // %a = trunc i32 %i to i8
8733 // %b = shl i8 %a, 6
8734 // %c = ashr i8 %b, 6
8735 // %d = sext i8 %c to i32
8736 // into:
8737 // %a = shl i32 %i, 30
8738 // %d = ashr i32 %a, 30
8739 Value *A = 0;
8740 ConstantInt *BA = 0, *CA = 0;
8741 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008742 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008743 BA == CA && isa<TruncInst>(A)) {
8744 Value *I = cast<TruncInst>(A)->getOperand(0);
8745 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008746 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8747 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008748 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008749 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008750 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8751 CI.getName()), CI);
8752 return BinaryOperator::CreateAShr(I, ShAmtV);
8753 }
8754 }
8755
Chris Lattnerba417832007-04-11 06:12:58 +00008756 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008757}
8758
Chris Lattnerb7530652008-01-27 05:29:54 +00008759/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8760/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008761static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008762 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008763 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008764 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008765 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8766 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008767 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008768 return 0;
8769}
8770
8771/// LookThroughFPExtensions - If this is an fp extension instruction, look
8772/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008773static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008774 if (Instruction *I = dyn_cast<Instruction>(V))
8775 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008776 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008777
8778 // If this value is a constant, return the constant in the smallest FP type
8779 // that can accurately represent it. This allows us to turn
8780 // (float)((double)X+2.0) into x+2.0f.
8781 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8782 if (CFP->getType() == Type::PPC_FP128Ty)
8783 return V; // No constant folding of this.
8784 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008785 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008786 return V;
8787 if (CFP->getType() == Type::DoubleTy)
8788 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008789 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008790 return V;
8791 // Don't try to shrink to various long double types.
8792 }
8793
8794 return V;
8795}
8796
8797Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8798 if (Instruction *I = commonCastTransforms(CI))
8799 return I;
8800
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008801 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008802 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008803 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 // many builtins (sqrt, etc).
8805 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8806 if (OpI && OpI->hasOneUse()) {
8807 switch (OpI->getOpcode()) {
8808 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008809 case Instruction::FAdd:
8810 case Instruction::FSub:
8811 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008812 case Instruction::FDiv:
8813 case Instruction::FRem:
8814 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008815 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8816 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008817 if (LHSTrunc->getType() != SrcTy &&
8818 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008819 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008820 // If the source types were both smaller than the destination type of
8821 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008822 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8823 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008824 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8825 CI.getType(), CI);
8826 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8827 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008828 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008829 }
8830 }
8831 break;
8832 }
8833 }
8834 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008835}
8836
8837Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8838 return commonCastTransforms(CI);
8839}
8840
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008841Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008842 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8843 if (OpI == 0)
8844 return commonCastTransforms(FI);
8845
8846 // fptoui(uitofp(X)) --> X
8847 // fptoui(sitofp(X)) --> X
8848 // This is safe if the intermediate type has enough bits in its mantissa to
8849 // accurately represent all values of X. For example, do not do this with
8850 // i64->float->i64. This is also safe for sitofp case, because any negative
8851 // 'X' value would cause an undefined result for the fptoui.
8852 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8853 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008854 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008855 OpI->getType()->getFPMantissaWidth())
8856 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008857
8858 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008859}
8860
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008861Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008862 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8863 if (OpI == 0)
8864 return commonCastTransforms(FI);
8865
8866 // fptosi(sitofp(X)) --> X
8867 // fptosi(uitofp(X)) --> X
8868 // This is safe if the intermediate type has enough bits in its mantissa to
8869 // accurately represent all values of X. For example, do not do this with
8870 // i64->float->i64. This is also safe for sitofp case, because any negative
8871 // 'X' value would cause an undefined result for the fptoui.
8872 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8873 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008874 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008875 OpI->getType()->getFPMantissaWidth())
8876 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008877
8878 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008879}
8880
8881Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8882 return commonCastTransforms(CI);
8883}
8884
8885Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8886 return commonCastTransforms(CI);
8887}
8888
Chris Lattnera0e69692009-03-24 18:35:40 +00008889Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8890 // If the destination integer type is smaller than the intptr_t type for
8891 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8892 // trunc to be exposed to other transforms. Don't do this for extending
8893 // ptrtoint's, because we don't know if the target sign or zero extends its
8894 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008895 if (TD &&
8896 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008897 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8898 TD->getIntPtrType(),
8899 "tmp"), CI);
8900 return new TruncInst(P, CI.getType());
8901 }
8902
Chris Lattnerd3e28342007-04-27 17:44:50 +00008903 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008904}
8905
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008906Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008907 // If the source integer type is larger than the intptr_t type for
8908 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8909 // allows the trunc to be exposed to other transforms. Don't do this for
8910 // extending inttoptr's, because we don't know if the target sign or zero
8911 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008912 if (TD &&
8913 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008914 TD->getPointerSizeInBits()) {
8915 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8916 TD->getIntPtrType(),
8917 "tmp"), CI);
8918 return new IntToPtrInst(P, CI.getType());
8919 }
8920
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008921 if (Instruction *I = commonCastTransforms(CI))
8922 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008923
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008924 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008925}
8926
Chris Lattnerd3e28342007-04-27 17:44:50 +00008927Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008928 // If the operands are integer typed then apply the integer transforms,
8929 // otherwise just apply the common ones.
8930 Value *Src = CI.getOperand(0);
8931 const Type *SrcTy = Src->getType();
8932 const Type *DestTy = CI.getType();
8933
Eli Friedman7e25d452009-07-13 20:53:00 +00008934 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935 if (Instruction *I = commonPointerCastTransforms(CI))
8936 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008937 } else {
8938 if (Instruction *Result = commonCastTransforms(CI))
8939 return Result;
8940 }
8941
8942
8943 // Get rid of casts from one type to the same type. These are useless and can
8944 // be replaced by the operand.
8945 if (DestTy == Src->getType())
8946 return ReplaceInstUsesWith(CI, Src);
8947
Reid Spencer3da59db2006-11-27 01:05:10 +00008948 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008949 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8950 const Type *DstElTy = DstPTy->getElementType();
8951 const Type *SrcElTy = SrcPTy->getElementType();
8952
Nate Begeman83ad90a2008-03-31 00:22:16 +00008953 // If the address spaces don't match, don't eliminate the bitcast, which is
8954 // required for changing types.
8955 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8956 return 0;
8957
Chris Lattnerd3e28342007-04-27 17:44:50 +00008958 // If we are casting a malloc or alloca to a pointer to a type of the same
8959 // size, rewrite the allocation instruction to allocate the "right" type.
8960 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8961 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8962 return V;
8963
Chris Lattnerd717c182007-05-05 22:32:24 +00008964 // If the source and destination are pointers, and this cast is equivalent
8965 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008966 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersona7235ea2009-07-31 20:28:14 +00008967 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008968 unsigned NumZeros = 0;
8969 while (SrcElTy != DstElTy &&
8970 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8971 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8972 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8973 ++NumZeros;
8974 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008975
Chris Lattnerd3e28342007-04-27 17:44:50 +00008976 // If we found a path from the src to dest, create the getelementptr now.
8977 if (SrcElTy == DstElTy) {
8978 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008979 Instruction *GEP = GetElementPtrInst::Create(Src,
8980 Idxs.begin(), Idxs.end(), "",
8981 ((Instruction*) NULL));
8982 cast<GEPOperator>(GEP)->setIsInBounds(true);
8983 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008984 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008985 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008986
Eli Friedman2451a642009-07-18 23:06:53 +00008987 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8988 if (DestVTy->getNumElements() == 1) {
8989 if (!isa<VectorType>(SrcTy)) {
8990 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8991 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008992 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Andersona7235ea2009-07-31 20:28:14 +00008993 Constant::getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00008994 }
8995 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8996 }
8997 }
8998
8999 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9000 if (SrcVTy->getNumElements() == 1) {
9001 if (!isa<VectorType>(DestTy)) {
9002 Instruction *Elem =
Owen Andersona7235ea2009-07-31 20:28:14 +00009003 ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
Eli Friedman2451a642009-07-18 23:06:53 +00009004 InsertNewInstBefore(Elem, CI);
9005 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9006 }
9007 }
9008 }
9009
Reid Spencer3da59db2006-11-27 01:05:10 +00009010 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9011 if (SVI->hasOneUse()) {
9012 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9013 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009014 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009015 cast<VectorType>(DestTy)->getNumElements() ==
9016 SVI->getType()->getNumElements() &&
9017 SVI->getType()->getNumElements() ==
9018 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009019 CastInst *Tmp;
9020 // If either of the operands is a cast from CI.getType(), then
9021 // evaluating the shuffle in the casted destination's type will allow
9022 // us to eliminate at least one cast.
9023 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9024 Tmp->getOperand(0)->getType() == DestTy) ||
9025 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9026 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009027 Value *LHS = InsertCastBefore(Instruction::BitCast,
9028 SVI->getOperand(0), DestTy, CI);
9029 Value *RHS = InsertCastBefore(Instruction::BitCast,
9030 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 // Return a new shuffle vector. Use the same element ID's, as we
9032 // know the vector types match #elts.
9033 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009034 }
9035 }
9036 }
9037 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009038 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009039}
9040
Chris Lattnere576b912004-04-09 23:46:01 +00009041/// GetSelectFoldableOperands - We want to turn code that looks like this:
9042/// %C = or %A, %B
9043/// %D = select %cond, %C, %A
9044/// into:
9045/// %C = select %cond, %B, 0
9046/// %D = or %A, %C
9047///
9048/// Assuming that the specified instruction is an operand to the select, return
9049/// a bitmask indicating which operands of this instruction are foldable if they
9050/// equal the other incoming value of the select.
9051///
9052static unsigned GetSelectFoldableOperands(Instruction *I) {
9053 switch (I->getOpcode()) {
9054 case Instruction::Add:
9055 case Instruction::Mul:
9056 case Instruction::And:
9057 case Instruction::Or:
9058 case Instruction::Xor:
9059 return 3; // Can fold through either operand.
9060 case Instruction::Sub: // Can only fold on the amount subtracted.
9061 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009062 case Instruction::LShr:
9063 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009064 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009065 default:
9066 return 0; // Cannot fold
9067 }
9068}
9069
9070/// GetSelectFoldableConstant - For the same transformation as the previous
9071/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009072static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009073 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009074 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009075 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009076 case Instruction::Add:
9077 case Instruction::Sub:
9078 case Instruction::Or:
9079 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009080 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009081 case Instruction::LShr:
9082 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009083 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009084 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009085 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009086 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009087 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009088 }
9089}
9090
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009091/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9092/// have the same opcode and only one use each. Try to simplify this.
9093Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9094 Instruction *FI) {
9095 if (TI->getNumOperands() == 1) {
9096 // If this is a non-volatile load or a cast from the same type,
9097 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009098 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009099 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9100 return 0;
9101 } else {
9102 return 0; // unknown unary op.
9103 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009104
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009105 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009106 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009107 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009108 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009109 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009110 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009111 }
9112
Reid Spencer832254e2007-02-02 02:16:23 +00009113 // Only handle binary operators here.
9114 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009115 return 0;
9116
9117 // Figure out if the operations have any operands in common.
9118 Value *MatchOp, *OtherOpT, *OtherOpF;
9119 bool MatchIsOpZero;
9120 if (TI->getOperand(0) == FI->getOperand(0)) {
9121 MatchOp = TI->getOperand(0);
9122 OtherOpT = TI->getOperand(1);
9123 OtherOpF = FI->getOperand(1);
9124 MatchIsOpZero = true;
9125 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9126 MatchOp = TI->getOperand(1);
9127 OtherOpT = TI->getOperand(0);
9128 OtherOpF = FI->getOperand(0);
9129 MatchIsOpZero = false;
9130 } else if (!TI->isCommutative()) {
9131 return 0;
9132 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9133 MatchOp = TI->getOperand(0);
9134 OtherOpT = TI->getOperand(1);
9135 OtherOpF = FI->getOperand(0);
9136 MatchIsOpZero = true;
9137 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9138 MatchOp = TI->getOperand(1);
9139 OtherOpT = TI->getOperand(0);
9140 OtherOpF = FI->getOperand(1);
9141 MatchIsOpZero = true;
9142 } else {
9143 return 0;
9144 }
9145
9146 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009147 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9148 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009149 InsertNewInstBefore(NewSI, SI);
9150
9151 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9152 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009153 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009154 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009155 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009156 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009157 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009158 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009159}
9160
Evan Chengde621922009-03-31 20:42:45 +00009161static bool isSelect01(Constant *C1, Constant *C2) {
9162 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9163 if (!C1I)
9164 return false;
9165 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9166 if (!C2I)
9167 return false;
9168 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9169}
9170
9171/// FoldSelectIntoOp - Try fold the select into one of the operands to
9172/// facilitate further optimization.
9173Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9174 Value *FalseVal) {
9175 // See the comment above GetSelectFoldableOperands for a description of the
9176 // transformation we are doing here.
9177 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9178 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9179 !isa<Constant>(FalseVal)) {
9180 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9181 unsigned OpToFold = 0;
9182 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9183 OpToFold = 1;
9184 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9185 OpToFold = 2;
9186 }
9187
9188 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009189 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009190 Value *OOp = TVI->getOperand(2-OpToFold);
9191 // Avoid creating select between 2 constants unless it's selecting
9192 // between 0 and 1.
9193 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9194 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9195 InsertNewInstBefore(NewSel, SI);
9196 NewSel->takeName(TVI);
9197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9198 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009199 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009200 }
9201 }
9202 }
9203 }
9204 }
9205
9206 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9207 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9208 !isa<Constant>(TrueVal)) {
9209 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9210 unsigned OpToFold = 0;
9211 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9212 OpToFold = 1;
9213 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9214 OpToFold = 2;
9215 }
9216
9217 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009218 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009219 Value *OOp = FVI->getOperand(2-OpToFold);
9220 // Avoid creating select between 2 constants unless it's selecting
9221 // between 0 and 1.
9222 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9223 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9224 InsertNewInstBefore(NewSel, SI);
9225 NewSel->takeName(FVI);
9226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9227 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009228 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009229 }
9230 }
9231 }
9232 }
9233 }
9234
9235 return 0;
9236}
9237
Dan Gohman81b28ce2008-09-16 18:46:06 +00009238/// visitSelectInstWithICmp - Visit a SelectInst that has an
9239/// ICmpInst as its first operand.
9240///
9241Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9242 ICmpInst *ICI) {
9243 bool Changed = false;
9244 ICmpInst::Predicate Pred = ICI->getPredicate();
9245 Value *CmpLHS = ICI->getOperand(0);
9246 Value *CmpRHS = ICI->getOperand(1);
9247 Value *TrueVal = SI.getTrueValue();
9248 Value *FalseVal = SI.getFalseValue();
9249
9250 // Check cases where the comparison is with a constant that
9251 // can be adjusted to fit the min/max idiom. We may edit ICI in
9252 // place here, so make sure the select is the only user.
9253 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009254 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009255 switch (Pred) {
9256 default: break;
9257 case ICmpInst::ICMP_ULT:
9258 case ICmpInst::ICMP_SLT: {
9259 // X < MIN ? T : F --> F
9260 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9261 return ReplaceInstUsesWith(SI, FalseVal);
9262 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009263 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009264 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9265 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9266 Pred = ICmpInst::getSwappedPredicate(Pred);
9267 CmpRHS = AdjustedRHS;
9268 std::swap(FalseVal, TrueVal);
9269 ICI->setPredicate(Pred);
9270 ICI->setOperand(1, CmpRHS);
9271 SI.setOperand(1, TrueVal);
9272 SI.setOperand(2, FalseVal);
9273 Changed = true;
9274 }
9275 break;
9276 }
9277 case ICmpInst::ICMP_UGT:
9278 case ICmpInst::ICMP_SGT: {
9279 // X > MAX ? T : F --> F
9280 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9281 return ReplaceInstUsesWith(SI, FalseVal);
9282 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009283 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009284 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286 Pred = ICmpInst::getSwappedPredicate(Pred);
9287 CmpRHS = AdjustedRHS;
9288 std::swap(FalseVal, TrueVal);
9289 ICI->setPredicate(Pred);
9290 ICI->setOperand(1, CmpRHS);
9291 SI.setOperand(1, TrueVal);
9292 SI.setOperand(2, FalseVal);
9293 Changed = true;
9294 }
9295 break;
9296 }
9297 }
9298
Dan Gohman1975d032008-10-30 20:40:10 +00009299 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9300 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009301 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009302 if (match(TrueVal, m_ConstantInt<-1>()) &&
9303 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009304 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009305 else if (match(TrueVal, m_ConstantInt<0>()) &&
9306 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009307 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9308
Dan Gohman1975d032008-10-30 20:40:10 +00009309 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9310 // If we are just checking for a icmp eq of a single bit and zext'ing it
9311 // to an integer, then shift the bit to the appropriate place and then
9312 // cast to integer to avoid the comparison.
9313 const APInt &Op1CV = CI->getValue();
9314
9315 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9316 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9317 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009318 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009319 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009320 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009321 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009322 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009323 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009324 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009325 if (In->getType() != SI.getType())
9326 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009327 true/*SExt*/, "tmp", ICI);
9328
9329 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009330 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009331 In->getName()+".not"), *ICI);
9332
9333 return ReplaceInstUsesWith(SI, In);
9334 }
9335 }
9336 }
9337
Dan Gohman81b28ce2008-09-16 18:46:06 +00009338 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9339 // Transform (X == Y) ? X : Y -> Y
9340 if (Pred == ICmpInst::ICMP_EQ)
9341 return ReplaceInstUsesWith(SI, FalseVal);
9342 // Transform (X != Y) ? X : Y -> X
9343 if (Pred == ICmpInst::ICMP_NE)
9344 return ReplaceInstUsesWith(SI, TrueVal);
9345 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9346
9347 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9348 // Transform (X == Y) ? Y : X -> X
9349 if (Pred == ICmpInst::ICMP_EQ)
9350 return ReplaceInstUsesWith(SI, FalseVal);
9351 // Transform (X != Y) ? Y : X -> Y
9352 if (Pred == ICmpInst::ICMP_NE)
9353 return ReplaceInstUsesWith(SI, TrueVal);
9354 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9355 }
9356
9357 /// NOTE: if we wanted to, this is where to detect integer ABS
9358
9359 return Changed ? &SI : 0;
9360}
9361
Chris Lattner3d69f462004-03-12 05:52:32 +00009362Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009363 Value *CondVal = SI.getCondition();
9364 Value *TrueVal = SI.getTrueValue();
9365 Value *FalseVal = SI.getFalseValue();
9366
9367 // select true, X, Y -> X
9368 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009369 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009370 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009371
9372 // select C, X, X -> X
9373 if (TrueVal == FalseVal)
9374 return ReplaceInstUsesWith(SI, TrueVal);
9375
Chris Lattnere87597f2004-10-16 18:11:37 +00009376 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9377 return ReplaceInstUsesWith(SI, FalseVal);
9378 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9379 return ReplaceInstUsesWith(SI, TrueVal);
9380 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9381 if (isa<Constant>(TrueVal))
9382 return ReplaceInstUsesWith(SI, TrueVal);
9383 else
9384 return ReplaceInstUsesWith(SI, FalseVal);
9385 }
9386
Reid Spencer4fe16d62007-01-11 18:21:29 +00009387 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009388 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009389 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009390 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009391 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009392 } else {
9393 // Change: A = select B, false, C --> A = and !B, C
9394 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009395 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009396 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009397 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009398 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009399 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009400 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009401 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009402 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009403 } else {
9404 // Change: A = select B, C, true --> A = or !B, C
9405 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009406 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009407 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009409 }
9410 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009411
9412 // select a, b, a -> a&b
9413 // select a, a, b -> a|b
9414 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009415 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009416 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009417 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009418 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009419
Chris Lattner2eefe512004-04-09 19:05:30 +00009420 // Selecting between two integer constants?
9421 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9422 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009423 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009424 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009425 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009426 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009427 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009428 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009429 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009430 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009431 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009432 }
Chris Lattner457dd822004-06-09 07:59:58 +00009433
Reid Spencere4d87aa2006-12-23 06:05:41 +00009434 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009435 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009436 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009437 // non-constant value, eliminate this whole mess. This corresponds to
9438 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009439 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009440 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009441 cast<Constant>(IC->getOperand(1))->isNullValue())
9442 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9443 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009444 isa<ConstantInt>(ICA->getOperand(1)) &&
9445 (ICA->getOperand(1) == TrueValC ||
9446 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009447 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9448 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009449 // know whether we have a icmp_ne or icmp_eq and whether the
9450 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009451 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009452 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009453 Value *V = ICA;
9454 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009455 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009456 Instruction::Xor, V, ICA->getOperand(1)), SI);
9457 return ReplaceInstUsesWith(SI, V);
9458 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009459 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009460 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009461
9462 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009463 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9464 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009465 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009466 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9467 // This is not safe in general for floating point:
9468 // consider X== -0, Y== +0.
9469 // It becomes safe if either operand is a nonzero constant.
9470 ConstantFP *CFPt, *CFPf;
9471 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9472 !CFPt->getValueAPF().isZero()) ||
9473 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9474 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009475 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009476 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009477 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009478 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009479 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009480 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009481
Reid Spencere4d87aa2006-12-23 06:05:41 +00009482 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009483 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009484 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9485 // This is not safe in general for floating point:
9486 // consider X== -0, Y== +0.
9487 // It becomes safe if either operand is a nonzero constant.
9488 ConstantFP *CFPt, *CFPf;
9489 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9490 !CFPt->getValueAPF().isZero()) ||
9491 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9492 !CFPf->getValueAPF().isZero()))
9493 return ReplaceInstUsesWith(SI, FalseVal);
9494 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009495 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009496 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9497 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009498 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009499 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009500 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009501 }
9502
9503 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009504 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9505 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9506 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009507
Chris Lattner87875da2005-01-13 22:52:24 +00009508 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9509 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9510 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009511 Instruction *AddOp = 0, *SubOp = 0;
9512
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009513 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9514 if (TI->getOpcode() == FI->getOpcode())
9515 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9516 return IV;
9517
9518 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9519 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009520 if ((TI->getOpcode() == Instruction::Sub &&
9521 FI->getOpcode() == Instruction::Add) ||
9522 (TI->getOpcode() == Instruction::FSub &&
9523 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009524 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009525 } else if ((FI->getOpcode() == Instruction::Sub &&
9526 TI->getOpcode() == Instruction::Add) ||
9527 (FI->getOpcode() == Instruction::FSub &&
9528 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009529 AddOp = TI; SubOp = FI;
9530 }
9531
9532 if (AddOp) {
9533 Value *OtherAddOp = 0;
9534 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9535 OtherAddOp = AddOp->getOperand(1);
9536 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9537 OtherAddOp = AddOp->getOperand(0);
9538 }
9539
9540 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009541 // So at this point we know we have (Y -> OtherAddOp):
9542 // select C, (add X, Y), (sub X, Z)
9543 Value *NegVal; // Compute -Z
9544 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009545 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009546 } else {
9547 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009548 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009549 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009550 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009551
9552 Value *NewTrueOp = OtherAddOp;
9553 Value *NewFalseOp = NegVal;
9554 if (AddOp != TI)
9555 std::swap(NewTrueOp, NewFalseOp);
9556 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009557 SelectInst::Create(CondVal, NewTrueOp,
9558 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009559
9560 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009561 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009562 }
9563 }
9564 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009565
Chris Lattnere576b912004-04-09 23:46:01 +00009566 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009567 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009568 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9569 if (FoldI)
9570 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009571 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009572
9573 if (BinaryOperator::isNot(CondVal)) {
9574 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9575 SI.setOperand(1, FalseVal);
9576 SI.setOperand(2, TrueVal);
9577 return &SI;
9578 }
9579
Chris Lattner3d69f462004-03-12 05:52:32 +00009580 return 0;
9581}
9582
Dan Gohmaneee962e2008-04-10 18:43:06 +00009583/// EnforceKnownAlignment - If the specified pointer points to an object that
9584/// we control, modify the object's alignment to PrefAlign. This isn't
9585/// often possible though. If alignment is important, a more reliable approach
9586/// is to simply align all global variables and allocation instructions to
9587/// their preferred alignment from the beginning.
9588///
9589static unsigned EnforceKnownAlignment(Value *V,
9590 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009591
Dan Gohmaneee962e2008-04-10 18:43:06 +00009592 User *U = dyn_cast<User>(V);
9593 if (!U) return Align;
9594
Dan Gohmanca178902009-07-17 20:47:02 +00009595 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009596 default: break;
9597 case Instruction::BitCast:
9598 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9599 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009600 // If all indexes are zero, it is just the alignment of the base pointer.
9601 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009602 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009603 if (!isa<Constant>(*i) ||
9604 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009605 AllZeroOperands = false;
9606 break;
9607 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009608
9609 if (AllZeroOperands) {
9610 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009611 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009612 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009613 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009614 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009615 }
9616
9617 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9618 // If there is a large requested alignment and we can, bump up the alignment
9619 // of the global.
9620 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009621 if (GV->getAlignment() >= PrefAlign)
9622 Align = GV->getAlignment();
9623 else {
9624 GV->setAlignment(PrefAlign);
9625 Align = PrefAlign;
9626 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009627 }
9628 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9629 // If there is a requested alignment and if this is an alloca, round up. We
9630 // don't do this for malloc, because some systems can't respect the request.
9631 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009632 if (AI->getAlignment() >= PrefAlign)
9633 Align = AI->getAlignment();
9634 else {
9635 AI->setAlignment(PrefAlign);
9636 Align = PrefAlign;
9637 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009638 }
9639 }
9640
9641 return Align;
9642}
9643
9644/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9645/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9646/// and it is more than the alignment of the ultimate object, see if we can
9647/// increase the alignment of the ultimate object, making this check succeed.
9648unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9649 unsigned PrefAlign) {
9650 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9651 sizeof(PrefAlign) * CHAR_BIT;
9652 APInt Mask = APInt::getAllOnesValue(BitWidth);
9653 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9654 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9655 unsigned TrailZ = KnownZero.countTrailingOnes();
9656 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9657
9658 if (PrefAlign > Align)
9659 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9660
9661 // We don't need to make any adjustment.
9662 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009663}
9664
Chris Lattnerf497b022008-01-13 23:50:23 +00009665Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009666 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009667 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009668 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009669 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009670
9671 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009672 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009673 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009674 return MI;
9675 }
9676
9677 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9678 // load/store.
9679 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9680 if (MemOpLength == 0) return 0;
9681
Chris Lattner37ac6082008-01-14 00:28:35 +00009682 // Source and destination pointer types are always "i8*" for intrinsic. See
9683 // if the size is something we can handle with a single primitive load/store.
9684 // A single load+store correctly handles overlapping memory in the memmove
9685 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009686 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009687 if (Size == 0) return MI; // Delete this mem transfer.
9688
9689 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009690 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009691
Chris Lattner37ac6082008-01-14 00:28:35 +00009692 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009693 Type *NewPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009694 PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009695
9696 // Memcpy forces the use of i8* for the source and destination. That means
9697 // that if you're using memcpy to move one double around, you'll get a cast
9698 // from double* to i8*. We'd much rather use a double load+store rather than
9699 // an i64 load+store, here because this improves the odds that the source or
9700 // dest address will be promotable. See if we can find a better type than the
9701 // integer datatype.
9702 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9703 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009704 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009705 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9706 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009707 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009708 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9709 if (STy->getNumElements() == 1)
9710 SrcETy = STy->getElementType(0);
9711 else
9712 break;
9713 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9714 if (ATy->getNumElements() == 1)
9715 SrcETy = ATy->getElementType();
9716 else
9717 break;
9718 } else
9719 break;
9720 }
9721
Dan Gohman8f8e2692008-05-23 01:52:21 +00009722 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009723 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009724 }
9725 }
9726
9727
Chris Lattnerf497b022008-01-13 23:50:23 +00009728 // If the memcpy/memmove provides better alignment info than we can
9729 // infer, use it.
9730 SrcAlign = std::max(SrcAlign, CopyAlign);
9731 DstAlign = std::max(DstAlign, CopyAlign);
9732
9733 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9734 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009735 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9736 InsertNewInstBefore(L, *MI);
9737 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9738
9739 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009740 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009741 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009742}
Chris Lattner3d69f462004-03-12 05:52:32 +00009743
Chris Lattner69ea9d22008-04-30 06:39:11 +00009744Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9745 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009746 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009747 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009748 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009749 return MI;
9750 }
9751
9752 // Extract the length and alignment and fill if they are constant.
9753 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9754 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9755 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9756 return 0;
9757 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009758 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009759
9760 // If the length is zero, this is a no-op
9761 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9762
9763 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9764 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersondebcb012009-07-29 22:17:13 +00009765 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009766
9767 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009768 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009769
9770 // Alignment 0 is identity for alignment 1 for memset, but not store.
9771 if (Alignment == 0) Alignment = 1;
9772
9773 // Extract the fill value and store.
9774 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009775 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009776 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009777
9778 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009779 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009780 return MI;
9781 }
9782
9783 return 0;
9784}
9785
9786
Chris Lattner8b0ea312006-01-13 20:11:04 +00009787/// visitCallInst - CallInst simplification. This mostly only handles folding
9788/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9789/// the heavy lifting.
9790///
Chris Lattner9fe38862003-06-19 17:00:31 +00009791Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009792 // If the caller function is nounwind, mark the call as nounwind, even if the
9793 // callee isn't.
9794 if (CI.getParent()->getParent()->doesNotThrow() &&
9795 !CI.doesNotThrow()) {
9796 CI.setDoesNotThrow();
9797 return &CI;
9798 }
9799
9800
9801
Chris Lattner8b0ea312006-01-13 20:11:04 +00009802 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9803 if (!II) return visitCallSite(&CI);
9804
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009805 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9806 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009807 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009808 bool Changed = false;
9809
9810 // memmove/cpy/set of zero bytes is a noop.
9811 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9812 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9813
Chris Lattner35b9e482004-10-12 04:52:52 +00009814 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009815 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009816 // Replace the instruction with just byte operations. We would
9817 // transform other cases to loads/stores, but we don't know if
9818 // alignment is sufficient.
9819 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009820 }
9821
Chris Lattner35b9e482004-10-12 04:52:52 +00009822 // If we have a memmove and the source operation is a constant global,
9823 // then the source and dest pointers can't alias, so we can change this
9824 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009825 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009826 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9827 if (GVSrc->isConstant()) {
9828 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009829 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9830 const Type *Tys[1];
9831 Tys[0] = CI.getOperand(3)->getType();
9832 CI.setOperand(0,
9833 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009834 Changed = true;
9835 }
Chris Lattnera935db82008-05-28 05:30:41 +00009836
9837 // memmove(x,x,size) -> noop.
9838 if (MMI->getSource() == MMI->getDest())
9839 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009840 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009841
Chris Lattner95a959d2006-03-06 20:18:44 +00009842 // If we can determine a pointer alignment that is bigger than currently
9843 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009844 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009845 if (Instruction *I = SimplifyMemTransfer(MI))
9846 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009847 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9848 if (Instruction *I = SimplifyMemSet(MSI))
9849 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009850 }
9851
Chris Lattner8b0ea312006-01-13 20:11:04 +00009852 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009853 }
9854
9855 switch (II->getIntrinsicID()) {
9856 default: break;
9857 case Intrinsic::bswap:
9858 // bswap(bswap(x)) -> x
9859 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9860 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9861 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9862 break;
9863 case Intrinsic::ppc_altivec_lvx:
9864 case Intrinsic::ppc_altivec_lvxl:
9865 case Intrinsic::x86_sse_loadu_ps:
9866 case Intrinsic::x86_sse2_loadu_pd:
9867 case Intrinsic::x86_sse2_loadu_dq:
9868 // Turn PPC lvx -> load if the pointer is known aligned.
9869 // Turn X86 loadups -> load if the pointer is known aligned.
9870 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9871 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009872 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009873 CI);
9874 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009875 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 break;
9877 case Intrinsic::ppc_altivec_stvx:
9878 case Intrinsic::ppc_altivec_stvxl:
9879 // Turn stvx -> store if the pointer is known aligned.
9880 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9881 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009882 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009883 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9884 return new StoreInst(II->getOperand(1), Ptr);
9885 }
9886 break;
9887 case Intrinsic::x86_sse_storeu_ps:
9888 case Intrinsic::x86_sse2_storeu_pd:
9889 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009890 // Turn X86 storeu -> store if the pointer is known aligned.
9891 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9892 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009893 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009894 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9895 return new StoreInst(II->getOperand(2), Ptr);
9896 }
9897 break;
9898
9899 case Intrinsic::x86_sse_cvttss2si: {
9900 // These intrinsics only demands the 0th element of its input vector. If
9901 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009902 unsigned VWidth =
9903 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9904 APInt DemandedElts(VWidth, 1);
9905 APInt UndefElts(VWidth, 0);
9906 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009907 UndefElts)) {
9908 II->setOperand(1, V);
9909 return II;
9910 }
9911 break;
9912 }
9913
9914 case Intrinsic::ppc_altivec_vperm:
9915 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9916 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9917 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009918
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 // Check that all of the elements are integer constants or undefs.
9920 bool AllEltsOk = true;
9921 for (unsigned i = 0; i != 16; ++i) {
9922 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9923 !isa<UndefValue>(Mask->getOperand(i))) {
9924 AllEltsOk = false;
9925 break;
9926 }
9927 }
9928
9929 if (AllEltsOk) {
9930 // Cast the input vectors to byte vectors.
9931 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9932 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009933 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009934
Chris Lattner0521e3c2008-06-18 04:33:20 +00009935 // Only extract each element once.
9936 Value *ExtractedElts[32];
9937 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9938
Chris Lattnere2ed0572006-04-06 19:19:17 +00009939 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009940 if (isa<UndefValue>(Mask->getOperand(i)))
9941 continue;
9942 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9943 Idx &= 31; // Match the hardware behavior.
9944
9945 if (ExtractedElts[Idx] == 0) {
9946 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009947 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneed707b2009-07-24 23:12:02 +00009948 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009949 InsertNewInstBefore(Elt, CI);
9950 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009951 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009952
Chris Lattner0521e3c2008-06-18 04:33:20 +00009953 // Insert this value into the result vector.
9954 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneed707b2009-07-24 23:12:02 +00009955 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009956 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009958 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009959 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009960 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009961 }
9962 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009963
Chris Lattner0521e3c2008-06-18 04:33:20 +00009964 case Intrinsic::stackrestore: {
9965 // If the save is right next to the restore, remove the restore. This can
9966 // happen when variable allocas are DCE'd.
9967 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9968 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9969 BasicBlock::iterator BI = SS;
9970 if (&*++BI == II)
9971 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009972 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009973 }
9974
9975 // Scan down this block to see if there is another stack restore in the
9976 // same block without an intervening call/alloca.
9977 BasicBlock::iterator BI = II;
9978 TerminatorInst *TI = II->getParent()->getTerminator();
9979 bool CannotRemove = false;
9980 for (++BI; &*BI != TI; ++BI) {
9981 if (isa<AllocaInst>(BI)) {
9982 CannotRemove = true;
9983 break;
9984 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009985 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9986 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9987 // If there is a stackrestore below this one, remove this one.
9988 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9989 return EraseInstFromFunction(CI);
9990 // Otherwise, ignore the intrinsic.
9991 } else {
9992 // If we found a non-intrinsic call, we can't remove the stack
9993 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009994 CannotRemove = true;
9995 break;
9996 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009997 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009998 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009999
10000 // If the stack restore is in a return/unwind block and if there are no
10001 // allocas or calls between the restore and the return, nuke the restore.
10002 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10003 return EraseInstFromFunction(CI);
10004 break;
10005 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010006 }
10007
Chris Lattner8b0ea312006-01-13 20:11:04 +000010008 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010009}
10010
10011// InvokeInst simplification
10012//
10013Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010014 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010015}
10016
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010017/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10018/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010019static bool isSafeToEliminateVarargsCast(const CallSite CS,
10020 const CastInst * const CI,
10021 const TargetData * const TD,
10022 const int ix) {
10023 if (!CI->isLosslessCast())
10024 return false;
10025
10026 // The size of ByVal arguments is derived from the type, so we
10027 // can't change to a type with a different size. If the size were
10028 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010029 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010030 return true;
10031
10032 const Type* SrcTy =
10033 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10034 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10035 if (!SrcTy->isSized() || !DstTy->isSized())
10036 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010037 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010038 return false;
10039 return true;
10040}
10041
Chris Lattnera44d8a22003-10-07 22:32:43 +000010042// visitCallSite - Improvements for call and invoke instructions.
10043//
10044Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010045 bool Changed = false;
10046
10047 // If the callee is a constexpr cast of a function, attempt to move the cast
10048 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010049 if (transformConstExprCastCall(CS)) return 0;
10050
Chris Lattner6c266db2003-10-07 22:54:13 +000010051 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010052
Chris Lattner08b22ec2005-05-13 07:09:09 +000010053 if (Function *CalleeF = dyn_cast<Function>(Callee))
10054 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10055 Instruction *OldCall = CS.getInstruction();
10056 // If the call and callee calling conventions don't match, this call must
10057 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010058 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010059 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010060 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010061 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010062 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010063 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10064 return EraseInstFromFunction(*OldCall);
10065 return 0;
10066 }
10067
Chris Lattner17be6352004-10-18 02:59:09 +000010068 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10069 // This instruction is not reachable, just remove it. We insert a store to
10070 // undef so that we know that this code is not reachable, despite the fact
10071 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010072 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010073 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010074 CS.getInstruction());
10075
10076 if (!CS.getInstruction()->use_empty())
10077 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010078 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010079
10080 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10081 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010082 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010083 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010084 }
Chris Lattner17be6352004-10-18 02:59:09 +000010085 return EraseInstFromFunction(*CS.getInstruction());
10086 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010087
Duncan Sandscdb6d922007-09-17 10:26:40 +000010088 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10089 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10090 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10091 return transformCallThroughTrampoline(CS);
10092
Chris Lattner6c266db2003-10-07 22:54:13 +000010093 const PointerType *PTy = cast<PointerType>(Callee->getType());
10094 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10095 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010096 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010097 // See if we can optimize any arguments passed through the varargs area of
10098 // the call.
10099 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010100 E = CS.arg_end(); I != E; ++I, ++ix) {
10101 CastInst *CI = dyn_cast<CastInst>(*I);
10102 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10103 *I = CI->getOperand(0);
10104 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010105 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010106 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010107 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010108
Duncan Sandsf0c33542007-12-19 21:13:37 +000010109 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010110 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010111 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010112 Changed = true;
10113 }
10114
Chris Lattner6c266db2003-10-07 22:54:13 +000010115 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010116}
10117
Chris Lattner9fe38862003-06-19 17:00:31 +000010118// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10119// attempt to move the cast to the arguments of the call/invoke.
10120//
10121bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10122 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10123 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010124 if (CE->getOpcode() != Instruction::BitCast ||
10125 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010126 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010127 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010128 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010129 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010130
10131 // Okay, this is a cast from a function to a different type. Unless doing so
10132 // would cause a type conversion of one of our arguments, change this call to
10133 // be a direct call with arguments casted to the appropriate types.
10134 //
10135 const FunctionType *FT = Callee->getFunctionType();
10136 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010137 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010138
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010139 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010140 return false; // TODO: Handle multiple return values.
10141
Chris Lattnerf78616b2004-01-14 06:06:08 +000010142 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010143 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010144 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010145 // Conversion is ok if changing from one pointer type to another or from
10146 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010147 !((isa<PointerType>(OldRetTy) || !TD ||
10148 OldRetTy == TD->getIntPtrType()) &&
10149 (isa<PointerType>(NewRetTy) || !TD ||
10150 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010151 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010152
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010153 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010154 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010155 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010156 return false; // Cannot transform this return value.
10157
Chris Lattner58d74912008-03-12 17:45:29 +000010158 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010159 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010160 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010161 return false; // Attribute not compatible with transformed value.
10162 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010163
Chris Lattnerf78616b2004-01-14 06:06:08 +000010164 // If the callsite is an invoke instruction, and the return value is used by
10165 // a PHI node in a successor, we cannot change the return type of the call
10166 // because there is no place to put the cast instruction (without breaking
10167 // the critical edge). Bail out in this case.
10168 if (!Caller->use_empty())
10169 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10170 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10171 UI != E; ++UI)
10172 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10173 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010174 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010175 return false;
10176 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010177
10178 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10179 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010180
Chris Lattner9fe38862003-06-19 17:00:31 +000010181 CallSite::arg_iterator AI = CS.arg_begin();
10182 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10183 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010184 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010185
10186 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010187 return false; // Cannot transform this parameter value.
10188
Devang Patel19c87462008-09-26 22:53:05 +000010189 if (CallerPAL.getParamAttributes(i + 1)
10190 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010191 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010192
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010193 // Converting from one pointer type to another or between a pointer and an
10194 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010195 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010196 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10197 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010198 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010199 }
10200
10201 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010202 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010203 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010204
Chris Lattner58d74912008-03-12 17:45:29 +000010205 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010207 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010208 // won't be dropping them. Check that these extra arguments have attributes
10209 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010210 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010212 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010213 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010214 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010215 return false;
10216 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010217
Chris Lattner9fe38862003-06-19 17:00:31 +000010218 // Okay, we decided that this is a safe thing to do: go ahead and start
10219 // inserting cast instructions as necessary...
10220 std::vector<Value*> Args;
10221 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010222 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010223 attrVec.reserve(NumCommonArgs);
10224
10225 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010226 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010227
10228 // If the return value is not being used, the type may not be compatible
10229 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010230 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231
10232 // Add the new return attributes.
10233 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010234 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010235
10236 AI = CS.arg_begin();
10237 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238 const Type *ParamTy = FT->getParamType(i);
10239 if ((*AI)->getType() == ParamTy) {
10240 Args.push_back(*AI);
10241 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010242 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010243 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010244 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010245 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010246 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010247
10248 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010249 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010250 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010251 }
10252
10253 // If the function takes more arguments than the call was taking, add them
10254 // now...
10255 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010256 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010257
10258 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010259 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010260 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010261 errs() << "WARNING: While resolving call to function '"
10262 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010263 } else {
10264 // Add all of the arguments in their promoted form to the arg list...
10265 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10266 const Type *PTy = getPromotedType((*AI)->getType());
10267 if (PTy != (*AI)->getType()) {
10268 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010269 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10270 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010271 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010272 InsertNewInstBefore(Cast, *Caller);
10273 Args.push_back(Cast);
10274 } else {
10275 Args.push_back(*AI);
10276 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010277
Duncan Sandse1e520f2008-01-13 08:02:44 +000010278 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010279 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010280 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010281 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010282 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010283 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010284
Devang Patel19c87462008-09-26 22:53:05 +000010285 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10286 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10287
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010288 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010289 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010290
Eric Christophera66297a2009-07-25 02:45:27 +000010291 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10292 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010293
Chris Lattner9fe38862003-06-19 17:00:31 +000010294 Instruction *NC;
10295 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010296 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010297 Args.begin(), Args.end(),
10298 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010299 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010300 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010301 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010302 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10303 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010304 CallInst *CI = cast<CallInst>(Caller);
10305 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010306 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010307 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010308 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010309 }
10310
Chris Lattner6934a042007-02-11 01:23:03 +000010311 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010313 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010314 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010315 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010316 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010317 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010318
10319 // If this is an invoke instruction, we should insert it after the first
10320 // non-phi, instruction in the normal successor block.
10321 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010322 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010323 InsertNewInstBefore(NC, *I);
10324 } else {
10325 // Otherwise, it's a call, just insert cast right after the call instr
10326 InsertNewInstBefore(NC, *Caller);
10327 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010328 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010329 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010330 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010331 }
10332 }
10333
10334 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10335 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010336 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010337 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010338 return true;
10339}
10340
Duncan Sandscdb6d922007-09-17 10:26:40 +000010341// transformCallThroughTrampoline - Turn a call to a function created by the
10342// init_trampoline intrinsic into a direct call to the underlying function.
10343//
10344Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10345 Value *Callee = CS.getCalledValue();
10346 const PointerType *PTy = cast<PointerType>(Callee->getType());
10347 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010348 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010349
10350 // If the call already has the 'nest' attribute somewhere then give up -
10351 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010352 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010353 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010354
10355 IntrinsicInst *Tramp =
10356 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10357
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010358 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010359 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10360 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10361
Devang Patel05988662008-09-25 21:00:45 +000010362 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010363 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010364 unsigned NestIdx = 1;
10365 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010366 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010367
10368 // Look for a parameter marked with the 'nest' attribute.
10369 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10370 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010371 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372 // Record the parameter type and any other attributes.
10373 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010374 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375 break;
10376 }
10377
10378 if (NestTy) {
10379 Instruction *Caller = CS.getInstruction();
10380 std::vector<Value*> NewArgs;
10381 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10382
Devang Patel05988662008-09-25 21:00:45 +000010383 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010384 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010385
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010387 // mean appending it. Likewise for attributes.
10388
Devang Patel19c87462008-09-26 22:53:05 +000010389 // Add any result attributes.
10390 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010391 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010392
Duncan Sandscdb6d922007-09-17 10:26:40 +000010393 {
10394 unsigned Idx = 1;
10395 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10396 do {
10397 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010398 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 Value *NestVal = Tramp->getOperand(3);
10400 if (NestVal->getType() != NestTy)
10401 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10402 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010403 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 }
10405
10406 if (I == E)
10407 break;
10408
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010409 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010411 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010412 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010413 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414
10415 ++Idx, ++I;
10416 } while (1);
10417 }
10418
Devang Patel19c87462008-09-26 22:53:05 +000010419 // Add any function attributes.
10420 if (Attributes Attr = Attrs.getFnAttributes())
10421 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10422
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423 // The trampoline may have been bitcast to a bogus type (FTy).
10424 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010425 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010426
Duncan Sandscdb6d922007-09-17 10:26:40 +000010427 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 NewTypes.reserve(FTy->getNumParams()+1);
10429
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010431 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010432 {
10433 unsigned Idx = 1;
10434 FunctionType::param_iterator I = FTy->param_begin(),
10435 E = FTy->param_end();
10436
10437 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010438 if (Idx == NestIdx)
10439 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010441
10442 if (I == E)
10443 break;
10444
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010445 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010447
10448 ++Idx, ++I;
10449 } while (1);
10450 }
10451
10452 // Replace the trampoline call with a direct call. Let the generic
10453 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010454 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010455 FTy->isVarArg());
10456 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010457 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010458 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010459 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010460 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10461 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010462
10463 Instruction *NewCaller;
10464 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010465 NewCaller = InvokeInst::Create(NewCallee,
10466 II->getNormalDest(), II->getUnwindDest(),
10467 NewArgs.begin(), NewArgs.end(),
10468 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010469 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010470 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010471 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010472 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10473 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010474 if (cast<CallInst>(Caller)->isTailCall())
10475 cast<CallInst>(NewCaller)->setTailCall();
10476 cast<CallInst>(NewCaller)->
10477 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010478 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 }
10480 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10481 Caller->replaceAllUsesWith(NewCaller);
10482 Caller->eraseFromParent();
10483 RemoveFromWorkList(Caller);
10484 return 0;
10485 }
10486 }
10487
10488 // Replace the trampoline call with a direct call. Since there is no 'nest'
10489 // parameter, there is no need to adjust the argument list. Let the generic
10490 // code sort out any function type mismatches.
10491 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010492 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010493 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010494 CS.setCalledFunction(NewCallee);
10495 return CS.getInstruction();
10496}
10497
Chris Lattner7da52b22006-11-01 04:51:18 +000010498/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10499/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10500/// and a single binop.
10501Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10502 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010503 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010504 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010505 Value *LHSVal = FirstInst->getOperand(0);
10506 Value *RHSVal = FirstInst->getOperand(1);
10507
10508 const Type *LHSType = LHSVal->getType();
10509 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010510
10511 // Scan to see if all operands are the same opcode, all have one use, and all
10512 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010513 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010514 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010515 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010516 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010517 // types or GEP's with different index types.
10518 I->getOperand(0)->getType() != LHSType ||
10519 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010520 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010521
10522 // If they are CmpInst instructions, check their predicates
10523 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10524 if (cast<CmpInst>(I)->getPredicate() !=
10525 cast<CmpInst>(FirstInst)->getPredicate())
10526 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010527
10528 // Keep track of which operand needs a phi node.
10529 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10530 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010531 }
10532
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010533 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010534
Chris Lattner7da52b22006-11-01 04:51:18 +000010535 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010536 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010537 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010538 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010539 NewLHS = PHINode::Create(LHSType,
10540 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010541 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10542 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010543 InsertNewInstBefore(NewLHS, PN);
10544 LHSVal = NewLHS;
10545 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010546
10547 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010548 NewRHS = PHINode::Create(RHSType,
10549 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010550 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10551 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010552 InsertNewInstBefore(NewRHS, PN);
10553 RHSVal = NewRHS;
10554 }
10555
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010556 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010557 if (NewLHS || NewRHS) {
10558 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10559 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10560 if (NewLHS) {
10561 Value *NewInLHS = InInst->getOperand(0);
10562 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10563 }
10564 if (NewRHS) {
10565 Value *NewInRHS = InInst->getOperand(1);
10566 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10567 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010568 }
10569 }
10570
Chris Lattner7da52b22006-11-01 04:51:18 +000010571 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010572 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010573 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010574 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10575 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010576}
10577
Chris Lattner05f18922008-12-01 02:34:36 +000010578Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10579 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10580
10581 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10582 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010583 // This is true if all GEP bases are allocas and if all indices into them are
10584 // constants.
10585 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010586
10587 // Scan to see if all operands are the same opcode, all have one use, and all
10588 // kill their operands (i.e. the operands have one use).
10589 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10590 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10591 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10592 GEP->getNumOperands() != FirstInst->getNumOperands())
10593 return 0;
10594
Chris Lattner36d3e322009-02-21 00:46:50 +000010595 // Keep track of whether or not all GEPs are of alloca pointers.
10596 if (AllBasePointersAreAllocas &&
10597 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10598 !GEP->hasAllConstantIndices()))
10599 AllBasePointersAreAllocas = false;
10600
Chris Lattner05f18922008-12-01 02:34:36 +000010601 // Compare the operand lists.
10602 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10603 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10604 continue;
10605
10606 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10607 // if one of the PHIs has a constant for the index. The index may be
10608 // substantially cheaper to compute for the constants, so making it a
10609 // variable index could pessimize the path. This also handles the case
10610 // for struct indices, which must always be constant.
10611 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10612 isa<ConstantInt>(GEP->getOperand(op)))
10613 return 0;
10614
10615 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10616 return 0;
10617 FixedOperands[op] = 0; // Needs a PHI.
10618 }
10619 }
10620
Chris Lattner36d3e322009-02-21 00:46:50 +000010621 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010622 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010623 // offset calculation, but all the predecessors will have to materialize the
10624 // stack address into a register anyway. We'd actually rather *clone* the
10625 // load up into the predecessors so that we have a load of a gep of an alloca,
10626 // which can usually all be folded into the load.
10627 if (AllBasePointersAreAllocas)
10628 return 0;
10629
Chris Lattner05f18922008-12-01 02:34:36 +000010630 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10631 // that is variable.
10632 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10633
10634 bool HasAnyPHIs = false;
10635 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10636 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10637 Value *FirstOp = FirstInst->getOperand(i);
10638 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10639 FirstOp->getName()+".pn");
10640 InsertNewInstBefore(NewPN, PN);
10641
10642 NewPN->reserveOperandSpace(e);
10643 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10644 OperandPhis[i] = NewPN;
10645 FixedOperands[i] = NewPN;
10646 HasAnyPHIs = true;
10647 }
10648
10649
10650 // Add all operands to the new PHIs.
10651 if (HasAnyPHIs) {
10652 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10653 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10654 BasicBlock *InBB = PN.getIncomingBlock(i);
10655
10656 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10657 if (PHINode *OpPhi = OperandPhis[op])
10658 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10659 }
10660 }
10661
10662 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010663 GetElementPtrInst *GEP =
10664 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10665 FixedOperands.end());
10666 if (cast<GEPOperator>(FirstInst)->isInBounds())
10667 cast<GEPOperator>(GEP)->setIsInBounds(true);
10668 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010669}
10670
10671
Chris Lattner21550882009-02-23 05:56:17 +000010672/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10673/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010674/// obvious the value of the load is not changed from the point of the load to
10675/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010676///
10677/// Finally, it is safe, but not profitable, to sink a load targetting a
10678/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10679/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010680static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010681 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10682
10683 for (++BBI; BBI != E; ++BBI)
10684 if (BBI->mayWriteToMemory())
10685 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010686
10687 // Check for non-address taken alloca. If not address-taken already, it isn't
10688 // profitable to do this xform.
10689 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10690 bool isAddressTaken = false;
10691 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10692 UI != E; ++UI) {
10693 if (isa<LoadInst>(UI)) continue;
10694 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10695 // If storing TO the alloca, then the address isn't taken.
10696 if (SI->getOperand(1) == AI) continue;
10697 }
10698 isAddressTaken = true;
10699 break;
10700 }
10701
Chris Lattner36d3e322009-02-21 00:46:50 +000010702 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010703 return false;
10704 }
10705
Chris Lattner36d3e322009-02-21 00:46:50 +000010706 // If this load is a load from a GEP with a constant offset from an alloca,
10707 // then we don't want to sink it. In its present form, it will be
10708 // load [constant stack offset]. Sinking it will cause us to have to
10709 // materialize the stack addresses in each predecessor in a register only to
10710 // do a shared load from register in the successor.
10711 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10712 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10713 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10714 return false;
10715
Chris Lattner76c73142006-11-01 07:13:54 +000010716 return true;
10717}
10718
Chris Lattner9fe38862003-06-19 17:00:31 +000010719
Chris Lattnerbac32862004-11-14 19:13:23 +000010720// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10721// operator and they all are only used by the PHI, PHI together their
10722// inputs, and do the operation once, to the result of the PHI.
10723Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10724 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10725
10726 // Scan the instruction, looking for input operations that can be folded away.
10727 // If all input operands to the phi are the same instruction (e.g. a cast from
10728 // the same type or "+42") we can pull the operation through the PHI, reducing
10729 // code size and simplifying code.
10730 Constant *ConstantOp = 0;
10731 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010732 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010733 if (isa<CastInst>(FirstInst)) {
10734 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010735 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010736 // Can fold binop, compare or shift here if the RHS is a constant,
10737 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010738 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010739 if (ConstantOp == 0)
10740 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010741 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10742 isVolatile = LI->isVolatile();
10743 // We can't sink the load if the loaded value could be modified between the
10744 // load and the PHI.
10745 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010746 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010747 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010748
10749 // If the PHI is of volatile loads and the load block has multiple
10750 // successors, sinking it would remove a load of the volatile value from
10751 // the path through the other successor.
10752 if (isVolatile &&
10753 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10754 return 0;
10755
Chris Lattner9c080502006-11-01 07:43:41 +000010756 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010757 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010758 } else {
10759 return 0; // Cannot fold this operation.
10760 }
10761
10762 // Check to see if all arguments are the same operation.
10763 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10764 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10765 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010766 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010767 return 0;
10768 if (CastSrcTy) {
10769 if (I->getOperand(0)->getType() != CastSrcTy)
10770 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010771 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010772 // We can't sink the load if the loaded value could be modified between
10773 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010774 if (LI->isVolatile() != isVolatile ||
10775 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010776 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010777 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010778
Chris Lattner71042962008-07-08 17:18:32 +000010779 // If the PHI is of volatile loads and the load block has multiple
10780 // successors, sinking it would remove a load of the volatile value from
10781 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010782 if (isVolatile &&
10783 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10784 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010785
Chris Lattnerbac32862004-11-14 19:13:23 +000010786 } else if (I->getOperand(1) != ConstantOp) {
10787 return 0;
10788 }
10789 }
10790
10791 // Okay, they are all the same operation. Create a new PHI node of the
10792 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010793 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10794 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010795 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010796
10797 Value *InVal = FirstInst->getOperand(0);
10798 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010799
10800 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010801 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10802 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10803 if (NewInVal != InVal)
10804 InVal = 0;
10805 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10806 }
10807
10808 Value *PhiVal;
10809 if (InVal) {
10810 // The new PHI unions all of the same values together. This is really
10811 // common, so we handle it intelligently here for compile-time speed.
10812 PhiVal = InVal;
10813 delete NewPN;
10814 } else {
10815 InsertNewInstBefore(NewPN, PN);
10816 PhiVal = NewPN;
10817 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010818
Chris Lattnerbac32862004-11-14 19:13:23 +000010819 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010820 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010821 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010822 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010823 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010824 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010825 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010826 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010827 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10828
10829 // If this was a volatile load that we are merging, make sure to loop through
10830 // and mark all the input loads as non-volatile. If we don't do this, we will
10831 // insert a new volatile load and the old ones will not be deletable.
10832 if (isVolatile)
10833 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10834 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10835
10836 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010837}
Chris Lattnera1be5662002-05-02 17:06:02 +000010838
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010839/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10840/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010841static bool DeadPHICycle(PHINode *PN,
10842 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010843 if (PN->use_empty()) return true;
10844 if (!PN->hasOneUse()) return false;
10845
10846 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010847 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010848 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010849
10850 // Don't scan crazily complex things.
10851 if (PotentiallyDeadPHIs.size() == 16)
10852 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010853
10854 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10855 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010856
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010857 return false;
10858}
10859
Chris Lattnercf5008a2007-11-06 21:52:06 +000010860/// PHIsEqualValue - Return true if this phi node is always equal to
10861/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10862/// z = some value; x = phi (y, z); y = phi (x, z)
10863static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10864 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10865 // See if we already saw this PHI node.
10866 if (!ValueEqualPHIs.insert(PN))
10867 return true;
10868
10869 // Don't scan crazily complex things.
10870 if (ValueEqualPHIs.size() == 16)
10871 return false;
10872
10873 // Scan the operands to see if they are either phi nodes or are equal to
10874 // the value.
10875 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10876 Value *Op = PN->getIncomingValue(i);
10877 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10878 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10879 return false;
10880 } else if (Op != NonPhiInVal)
10881 return false;
10882 }
10883
10884 return true;
10885}
10886
10887
Chris Lattner473945d2002-05-06 18:06:38 +000010888// PHINode simplification
10889//
Chris Lattner7e708292002-06-25 16:13:24 +000010890Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010891 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010892 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010893
Owen Anderson7e057142006-07-10 22:03:18 +000010894 if (Value *V = PN.hasConstantValue())
10895 return ReplaceInstUsesWith(PN, V);
10896
Owen Anderson7e057142006-07-10 22:03:18 +000010897 // If all PHI operands are the same operation, pull them through the PHI,
10898 // reducing code size.
10899 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010900 isa<Instruction>(PN.getIncomingValue(1)) &&
10901 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10902 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10903 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10904 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010905 PN.getIncomingValue(0)->hasOneUse())
10906 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10907 return Result;
10908
10909 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10910 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10911 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010912 if (PN.hasOneUse()) {
10913 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10914 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010915 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010916 PotentiallyDeadPHIs.insert(&PN);
10917 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010918 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010919 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010920
10921 // If this phi has a single use, and if that use just computes a value for
10922 // the next iteration of a loop, delete the phi. This occurs with unused
10923 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10924 // common case here is good because the only other things that catch this
10925 // are induction variable analysis (sometimes) and ADCE, which is only run
10926 // late.
10927 if (PHIUser->hasOneUse() &&
10928 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10929 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010930 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010931 }
10932 }
Owen Anderson7e057142006-07-10 22:03:18 +000010933
Chris Lattnercf5008a2007-11-06 21:52:06 +000010934 // We sometimes end up with phi cycles that non-obviously end up being the
10935 // same value, for example:
10936 // z = some value; x = phi (y, z); y = phi (x, z)
10937 // where the phi nodes don't necessarily need to be in the same block. Do a
10938 // quick check to see if the PHI node only contains a single non-phi value, if
10939 // so, scan to see if the phi cycle is actually equal to that value.
10940 {
10941 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10942 // Scan for the first non-phi operand.
10943 while (InValNo != NumOperandVals &&
10944 isa<PHINode>(PN.getIncomingValue(InValNo)))
10945 ++InValNo;
10946
10947 if (InValNo != NumOperandVals) {
10948 Value *NonPhiInVal = PN.getOperand(InValNo);
10949
10950 // Scan the rest of the operands to see if there are any conflicts, if so
10951 // there is no need to recursively scan other phis.
10952 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10953 Value *OpVal = PN.getIncomingValue(InValNo);
10954 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10955 break;
10956 }
10957
10958 // If we scanned over all operands, then we have one unique value plus
10959 // phi values. Scan PHI nodes to see if they all merge in each other or
10960 // the value.
10961 if (InValNo == NumOperandVals) {
10962 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10963 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10964 return ReplaceInstUsesWith(PN, NonPhiInVal);
10965 }
10966 }
10967 }
Chris Lattner60921c92003-12-19 05:58:40 +000010968 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010969}
10970
Reid Spencer17212df2006-12-12 09:18:51 +000010971static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10972 Instruction *InsertPoint,
10973 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010974 unsigned PtrSize = DTy->getScalarSizeInBits();
10975 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010976 // We must cast correctly to the pointer type. Ensure that we
10977 // sign extend the integer value if it is smaller as this is
10978 // used for address computation.
10979 Instruction::CastOps opcode =
10980 (VTySize < PtrSize ? Instruction::SExt :
10981 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10982 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010983}
10984
Chris Lattnera1be5662002-05-02 17:06:02 +000010985
Chris Lattner7e708292002-06-25 16:13:24 +000010986Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010987 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010988 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010989 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010990 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010991 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010992
Chris Lattnere87597f2004-10-16 18:11:37 +000010993 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010994 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010995
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010996 bool HasZeroPointerIndex = false;
10997 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10998 HasZeroPointerIndex = C->isNullValue();
10999
11000 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011001 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011002
Chris Lattner28977af2004-04-05 01:30:19 +000011003 // Eliminate unneeded casts for indices.
11004 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011005
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011006 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011007 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11008 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011009 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011010 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011011 if (CI->getOpcode() == Instruction::ZExt ||
11012 CI->getOpcode() == Instruction::SExt) {
11013 const Type *SrcTy = CI->getOperand(0)->getType();
11014 // We can eliminate a cast from i32 to i64 iff the target
11015 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011016 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011017 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011018 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011019 }
11020 }
11021 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011022 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011023 // to what we need. If narrower, sign-extend it to what we need.
11024 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011025 // insert it. This explicit cast can make subsequent optimizations more
11026 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011027 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011028 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011029 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000011030 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011031 MadeChange = true;
11032 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011033 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11034 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011035 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011036 MadeChange = true;
11037 }
Eric Christophera66297a2009-07-25 02:45:27 +000011038 } else if (TD->getTypeSizeInBits(Op->getType())
11039 < TD->getPointerSizeInBits()) {
Dan Gohman4f833d42008-09-11 23:06:38 +000011040 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000011041 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011042 MadeChange = true;
11043 } else {
11044 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11045 GEP);
11046 *i = Op;
11047 MadeChange = true;
11048 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011049 }
Chris Lattner28977af2004-04-05 01:30:19 +000011050 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011051 }
Chris Lattner28977af2004-04-05 01:30:19 +000011052 if (MadeChange) return &GEP;
11053
Chris Lattner90ac28c2002-08-02 19:29:35 +000011054 // Combine Indices - If the source pointer to this getelementptr instruction
11055 // is a getelementptr instruction, combine the indices of the two
11056 // getelementptr instructions into a single instruction.
11057 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011058 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011059 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11060 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner72588fc2007-02-15 22:48:32 +000011061 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011062 if (!Src->isInBounds())
11063 BothInBounds = false;
11064 }
Chris Lattnerebd985c2004-03-25 22:59:29 +000011065
11066 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011067 // Note that if our source is a gep chain itself that we wait for that
11068 // chain to be resolved before we perform this transformation. This
11069 // avoids us creating a TON of code in some cases.
11070 //
11071 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11072 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11073 return 0; // Wait until our source is folded to completion.
11074
Chris Lattner72588fc2007-02-15 22:48:32 +000011075 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011076
11077 // Find out whether the last index in the source GEP is a sequential idx.
11078 bool EndsWithSequential = false;
11079 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11080 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011081 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011082
Chris Lattner90ac28c2002-08-02 19:29:35 +000011083 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011084 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011085 // Replace: gep (gep %P, long B), long A, ...
11086 // With: T = long A+B; gep %P, T, ...
11087 //
Chris Lattner620ce142004-05-07 22:09:22 +000011088 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011089 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011090 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011091 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011092 Sum = SO1;
11093 } else {
11094 // If they aren't the same type, convert both to an integer of the
11095 // target's pointer size.
11096 if (SO1->getType() != GO1->getType()) {
11097 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011098 SO1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011099 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011100 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011101 GO1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011102 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011103 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011104 unsigned PS = TD->getPointerSizeInBits();
11105 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011106 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011107 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011108
Duncan Sands514ab342007-11-01 20:53:16 +000011109 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011110 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011111 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011112 } else {
11113 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011114 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11115 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011116 }
11117 }
11118 }
Chris Lattner620ce142004-05-07 22:09:22 +000011119 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011120 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Andersond672ecb2009-07-03 00:17:18 +000011121 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011122 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011123 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011124 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011125 }
Chris Lattner28977af2004-04-05 01:30:19 +000011126 }
Chris Lattner620ce142004-05-07 22:09:22 +000011127
11128 // Recycle the GEP we already have if possible.
11129 if (SrcGEPOperands.size() == 2) {
11130 GEP.setOperand(0, SrcGEPOperands[0]);
11131 GEP.setOperand(1, Sum);
11132 return &GEP;
11133 } else {
11134 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11135 SrcGEPOperands.end()-1);
11136 Indices.push_back(Sum);
11137 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11138 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011139 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011140 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011141 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011142 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011143 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11144 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011145 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11146 }
11147
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011148 if (!Indices.empty()) {
11149 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11150 Indices.begin(),
11151 Indices.end(),
11152 GEP.getName());
11153 if (BothInBounds)
11154 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11155 return NewGEP;
11156 }
Chris Lattner9b761232002-08-17 22:21:59 +000011157
Chris Lattner620ce142004-05-07 22:09:22 +000011158 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011159 // GEP of global variable. If all of the indices for this GEP are
11160 // constants, we can promote this to a constexpr instead of an instruction.
11161
11162 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011163 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011164 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11165 for (; I != E && isa<Constant>(*I); ++I)
11166 Indices.push_back(cast<Constant>(*I));
11167
11168 if (I == E) { // If they are all constants...
Owen Andersonbaf3c402009-07-29 18:55:55 +000011169 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011170 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011171
11172 // Replace all uses of the GEP with the new constexpr...
11173 return ReplaceInstUsesWith(GEP, CE);
11174 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011175 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011176 if (!isa<PointerType>(X->getType())) {
11177 // Not interesting. Source pointer must be a cast from pointer.
11178 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011179 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11180 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011181 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011182 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11183 // into : GEP i8* X, ...
11184 //
Chris Lattnereed48272005-09-13 00:40:14 +000011185 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011186 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11187 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011188 if (const ArrayType *CATy =
11189 dyn_cast<ArrayType>(CPTy->getElementType())) {
11190 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11191 if (CATy->getElementType() == XTy->getElementType()) {
11192 // -> GEP i8* X, ...
11193 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011194 GetElementPtrInst *NewGEP =
11195 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11196 GEP.getName());
11197 if (cast<GEPOperator>(&GEP)->isInBounds())
11198 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11199 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011200 } else if (const ArrayType *XATy =
11201 dyn_cast<ArrayType>(XTy->getElementType())) {
11202 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011203 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011204 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011205 // At this point, we know that the cast source type is a pointer
11206 // to an array of the same type as the destination pointer
11207 // array. Because the array type is never stepped over (there
11208 // is a leading zero) we can fold the cast into this GEP.
11209 GEP.setOperand(0, X);
11210 return &GEP;
11211 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011212 }
11213 }
Chris Lattnereed48272005-09-13 00:40:14 +000011214 } else if (GEP.getNumOperands() == 2) {
11215 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011216 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11217 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011218 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11219 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011220 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011221 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11222 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011223 Value *Idx[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011224 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011225 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011226 GetElementPtrInst *NewGEP =
11227 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11228 if (cast<GEPOperator>(&GEP)->isInBounds())
11229 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11230 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011231 // V and GEP are both pointer types --> BitCast
11232 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011233 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011234
11235 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011236 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011237 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011238 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011239
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011240 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011241 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011242 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011243
11244 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11245 // allow either a mul, shift, or constant here.
11246 Value *NewIdx = 0;
11247 ConstantInt *Scale = 0;
11248 if (ArrayEltSize == 1) {
11249 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011250 Scale =
Owen Andersoneed707b2009-07-24 23:12:02 +000011251 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011252 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011253 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011254 Scale = CI;
11255 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11256 if (Inst->getOpcode() == Instruction::Shl &&
11257 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011258 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11259 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011260 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011261 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011262 NewIdx = Inst->getOperand(0);
11263 } else if (Inst->getOpcode() == Instruction::Mul &&
11264 isa<ConstantInt>(Inst->getOperand(1))) {
11265 Scale = cast<ConstantInt>(Inst->getOperand(1));
11266 NewIdx = Inst->getOperand(0);
11267 }
11268 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011269
Chris Lattner7835cdd2005-09-13 18:36:04 +000011270 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011271 // out, perform the transformation. Note, we don't know whether Scale is
11272 // signed or not. We'll use unsigned version of division/modulo
11273 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011274 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011275 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011276 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011277 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011278 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011279 Constant *C =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011280 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011281 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011282 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011283 NewIdx = InsertNewInstBefore(Sc, GEP);
11284 }
11285
11286 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011287 Value *Idx[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011288 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011289 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011290 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011291 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011292 if (cast<GEPOperator>(&GEP)->isInBounds())
11293 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011294 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11295 // The NewGEP must be pointer typed, so must the old one -> BitCast
11296 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011297 }
11298 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011299 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011300 }
Chris Lattner58407792009-01-09 04:53:57 +000011301
Chris Lattner46cd5a12009-01-09 05:44:56 +000011302 /// See if we can simplify:
11303 /// X = bitcast A to B*
11304 /// Y = gep X, <...constant indices...>
11305 /// into a gep of the original struct. This is important for SROA and alias
11306 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011307 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011308 if (TD &&
11309 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011310 // Determine how much the GEP moves the pointer. We are guaranteed to get
11311 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011312 ConstantInt *OffsetV =
11313 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011314 int64_t Offset = OffsetV->getSExtValue();
11315
11316 // If this GEP instruction doesn't move the pointer, just replace the GEP
11317 // with a bitcast of the real input to the dest type.
11318 if (Offset == 0) {
11319 // If the bitcast is of an allocation, and the allocation will be
11320 // converted to match the type of the cast, don't touch this.
11321 if (isa<AllocationInst>(BCI->getOperand(0))) {
11322 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11323 if (Instruction *I = visitBitCast(*BCI)) {
11324 if (I != BCI) {
11325 I->takeName(BCI);
11326 BCI->getParent()->getInstList().insert(BCI, I);
11327 ReplaceInstUsesWith(*BCI, I);
11328 }
11329 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011330 }
Chris Lattner58407792009-01-09 04:53:57 +000011331 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011332 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011333 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011334
11335 // Otherwise, if the offset is non-zero, we need to find out if there is a
11336 // field at Offset in 'A's type. If so, we can pull the cast through the
11337 // GEP.
11338 SmallVector<Value*, 8> NewIndices;
11339 const Type *InTy =
11340 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011341 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011342 Instruction *NGEP =
11343 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11344 NewIndices.end());
11345 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011346 if (cast<GEPOperator>(&GEP)->isInBounds())
11347 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011348 InsertNewInstBefore(NGEP, GEP);
11349 NGEP->takeName(&GEP);
11350 return new BitCastInst(NGEP, GEP.getType());
11351 }
Chris Lattner58407792009-01-09 04:53:57 +000011352 }
11353 }
11354
Chris Lattner8a2a3112001-12-14 16:52:21 +000011355 return 0;
11356}
11357
Chris Lattner0864acf2002-11-04 16:18:53 +000011358Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11359 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011360 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011361 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11362 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011363 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011364 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011365
11366 // Create and insert the replacement instruction...
11367 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011368 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011369 else {
11370 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011371 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011372 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011373
11374 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011375
Chris Lattner0864acf2002-11-04 16:18:53 +000011376 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011377 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011378 //
11379 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011380 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011381
11382 // Now that I is pointing to the first non-allocation-inst in the block,
11383 // insert our getelementptr instruction...
11384 //
Owen Andersona7235ea2009-07-31 20:28:14 +000011385 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011386 Value *Idx[2];
11387 Idx[0] = NullIdx;
11388 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011389 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11390 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011391 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011392
11393 // Now make everything use the getelementptr instead of the original
11394 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011395 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011396 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011397 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011398 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011399 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011400
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011401 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011402 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011403 // Note that we only do this for alloca's, because malloc should allocate
11404 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011405 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011406 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011407
11408 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11409 if (AI.getAlignment() == 0)
11410 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11411 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011412
Chris Lattner0864acf2002-11-04 16:18:53 +000011413 return 0;
11414}
11415
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011416Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11417 Value *Op = FI.getOperand(0);
11418
Chris Lattner17be6352004-10-18 02:59:09 +000011419 // free undef -> unreachable.
11420 if (isa<UndefValue>(Op)) {
11421 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011422 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011423 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011424 return EraseInstFromFunction(FI);
11425 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011426
Chris Lattner6160e852004-02-28 04:57:37 +000011427 // If we have 'free null' delete the instruction. This can happen in stl code
11428 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011429 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011430 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011431
11432 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11433 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11434 FI.setOperand(0, CI->getOperand(0));
11435 return &FI;
11436 }
11437
11438 // Change free (gep X, 0,0,0,0) into free(X)
11439 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11440 if (GEPI->hasAllZeroIndices()) {
11441 AddToWorkList(GEPI);
11442 FI.setOperand(0, GEPI->getOperand(0));
11443 return &FI;
11444 }
11445 }
11446
11447 // Change free(malloc) into nothing, if the malloc has a single use.
11448 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11449 if (MI->hasOneUse()) {
11450 EraseInstFromFunction(FI);
11451 return EraseInstFromFunction(*MI);
11452 }
Chris Lattner6160e852004-02-28 04:57:37 +000011453
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011454 return 0;
11455}
11456
11457
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011458/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011459static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011460 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011461 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011462 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011463 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011464
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011465 if (TD) {
11466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11467 // Instead of loading constant c string, use corresponding integer value
11468 // directly if string length is small enough.
11469 std::string Str;
11470 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11471 unsigned len = Str.length();
11472 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11473 unsigned numBits = Ty->getPrimitiveSizeInBits();
11474 // Replace LI with immediate integer store.
11475 if ((numBits >> 3) == len + 1) {
11476 APInt StrVal(numBits, 0);
11477 APInt SingleChar(numBits, 0);
11478 if (TD->isLittleEndian()) {
11479 for (signed i = len-1; i >= 0; i--) {
11480 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11481 StrVal = (StrVal << 8) | SingleChar;
11482 }
11483 } else {
11484 for (unsigned i = 0; i < len; i++) {
11485 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11486 StrVal = (StrVal << 8) | SingleChar;
11487 }
11488 // Append NULL at the end.
11489 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011490 StrVal = (StrVal << 8) | SingleChar;
11491 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011492 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011493 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011494 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011495 }
11496 }
11497 }
11498
Mon P Wang6753f952009-02-07 22:19:29 +000011499 const PointerType *DestTy = cast<PointerType>(CI->getType());
11500 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011501 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011502
11503 // If the address spaces don't match, don't eliminate the cast.
11504 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11505 return 0;
11506
Chris Lattnerb89e0712004-07-13 01:49:43 +000011507 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011508
Reid Spencer42230162007-01-22 05:51:25 +000011509 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011510 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011511 // If the source is an array, the code below will not succeed. Check to
11512 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11513 // constants.
11514 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11515 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11516 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011517 Value *Idxs[2];
Owen Andersona7235ea2009-07-31 20:28:14 +000011518 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
Owen Andersonbaf3c402009-07-29 18:55:55 +000011519 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011520 SrcTy = cast<PointerType>(CastOp->getType());
11521 SrcPTy = SrcTy->getElementType();
11522 }
11523
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011524 if (IC.getTargetData() &&
11525 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011526 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011527 // Do not allow turning this into a load of an integer, which is then
11528 // casted to a pointer, this pessimizes pointer analysis a lot.
11529 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011530 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11531 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011532
Chris Lattnerf9527852005-01-31 04:50:46 +000011533 // Okay, we are casting from one integer or pointer type to another of
11534 // the same size. Instead of casting the pointer before the load, cast
11535 // the result of the loaded value.
11536 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11537 CI->getName(),
11538 LI.isVolatile()),LI);
11539 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011540 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011541 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011542 }
11543 }
11544 return 0;
11545}
11546
Chris Lattner833b8a42003-06-26 05:06:25 +000011547Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11548 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011549
Dan Gohman9941f742007-07-20 16:34:21 +000011550 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011551 if (TD) {
11552 unsigned KnownAlign =
11553 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11554 if (KnownAlign >
11555 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11556 LI.getAlignment()))
11557 LI.setAlignment(KnownAlign);
11558 }
Dan Gohman9941f742007-07-20 16:34:21 +000011559
Chris Lattner37366c12005-05-01 04:24:53 +000011560 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011561 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011562 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011563 return Res;
11564
11565 // None of the following transforms are legal for volatile loads.
11566 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011567
Dan Gohman2276a7b2008-10-15 23:19:35 +000011568 // Do really simple store-to-load forwarding and load CSE, to catch cases
11569 // where there are several consequtive memory accesses to the same location,
11570 // separated by a few arithmetic operations.
11571 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011572 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11573 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011574
Christopher Lambb15147e2007-12-29 07:56:53 +000011575 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11576 const Value *GEPI0 = GEPI->getOperand(0);
11577 // TODO: Consider a target hook for valid address spaces for this xform.
11578 if (isa<ConstantPointerNull>(GEPI0) &&
11579 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011580 // Insert a new store to null instruction before the load to indicate
11581 // that this code is not reachable. We do this instead of inserting
11582 // an unreachable instruction directly because we cannot modify the
11583 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011584 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011585 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011586 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011587 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011588 }
Chris Lattner37366c12005-05-01 04:24:53 +000011589
Chris Lattnere87597f2004-10-16 18:11:37 +000011590 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011591 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011592 // TODO: Consider a target hook for valid address spaces for this xform.
11593 if (isa<UndefValue>(C) || (C->isNullValue() &&
11594 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011595 // Insert a new store to null instruction before the load to indicate that
11596 // this code is not reachable. We do this instead of inserting an
11597 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011598 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011599 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011600 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011601 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011602
Chris Lattnere87597f2004-10-16 18:11:37 +000011603 // Instcombine load (constant global) into the value loaded.
11604 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011605 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011606 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011607
Chris Lattnere87597f2004-10-16 18:11:37 +000011608 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011610 if (CE->getOpcode() == Instruction::GetElementPtr) {
11611 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011612 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011613 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011614 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011615 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011616 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011617 if (CE->getOperand(0)->isNullValue()) {
11618 // Insert a new store to null instruction before the load to indicate
11619 // that this code is not reachable. We do this instead of inserting
11620 // an unreachable instruction directly because we cannot modify the
11621 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011622 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011623 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011624 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011625 }
11626
Reid Spencer3da59db2006-11-27 01:05:10 +000011627 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011628 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011629 return Res;
11630 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011631 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011632 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011633
11634 // If this load comes from anywhere in a constant global, and if the global
11635 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011636 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011637 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011638 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011639 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011640 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011641 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011642 }
11643 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011644
Chris Lattner37366c12005-05-01 04:24:53 +000011645 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011646 // Change select and PHI nodes to select values instead of addresses: this
11647 // helps alias analysis out a lot, allows many others simplifications, and
11648 // exposes redundancy in the code.
11649 //
11650 // Note that we cannot do the transformation unless we know that the
11651 // introduced loads cannot trap! Something like this is valid as long as
11652 // the condition is always false: load (select bool %C, int* null, int* %G),
11653 // but it would not be valid if we transformed it to load from null
11654 // unconditionally.
11655 //
11656 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11657 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011658 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11659 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011660 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011661 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011662 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011663 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011664 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011665 }
11666
Chris Lattner684fe212004-09-23 15:46:00 +000011667 // load (select (cond, null, P)) -> load P
11668 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11669 if (C->isNullValue()) {
11670 LI.setOperand(0, SI->getOperand(2));
11671 return &LI;
11672 }
11673
11674 // load (select (cond, P, null)) -> load P
11675 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11676 if (C->isNullValue()) {
11677 LI.setOperand(0, SI->getOperand(1));
11678 return &LI;
11679 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011680 }
11681 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011682 return 0;
11683}
11684
Reid Spencer55af2b52007-01-19 21:20:31 +000011685/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011686/// when possible. This makes it generally easy to do alias analysis and/or
11687/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011688static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11689 User *CI = cast<User>(SI.getOperand(1));
11690 Value *CastOp = CI->getOperand(0);
11691
11692 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011693 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11694 if (SrcTy == 0) return 0;
11695
11696 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011697
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011698 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11699 return 0;
11700
Chris Lattner3914f722009-01-24 01:00:13 +000011701 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11702 /// to its first element. This allows us to handle things like:
11703 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11704 /// on 32-bit hosts.
11705 SmallVector<Value*, 4> NewGEPIndices;
11706
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011707 // If the source is an array, the code below will not succeed. Check to
11708 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11709 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011710 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11711 // Index through pointer.
Owen Andersona7235ea2009-07-31 20:28:14 +000011712 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011713 NewGEPIndices.push_back(Zero);
11714
11715 while (1) {
11716 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011717 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011718 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011719 NewGEPIndices.push_back(Zero);
11720 SrcPTy = STy->getElementType(0);
11721 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11722 NewGEPIndices.push_back(Zero);
11723 SrcPTy = ATy->getElementType();
11724 } else {
11725 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011726 }
Chris Lattner3914f722009-01-24 01:00:13 +000011727 }
11728
Owen Andersondebcb012009-07-29 22:17:13 +000011729 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011730 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011731
11732 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11733 return 0;
11734
Chris Lattner71759c42009-01-16 20:12:52 +000011735 // If the pointers point into different address spaces or if they point to
11736 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011737 if (!IC.getTargetData() ||
11738 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011739 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011740 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11741 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011742 return 0;
11743
11744 // Okay, we are casting from one integer or pointer type to another of
11745 // the same size. Instead of casting the pointer before
11746 // the store, cast the value to be stored.
11747 Value *NewCast;
11748 Value *SIOp0 = SI.getOperand(0);
11749 Instruction::CastOps opcode = Instruction::BitCast;
11750 const Type* CastSrcTy = SIOp0->getType();
11751 const Type* CastDstTy = SrcPTy;
11752 if (isa<PointerType>(CastDstTy)) {
11753 if (CastSrcTy->isInteger())
11754 opcode = Instruction::IntToPtr;
11755 } else if (isa<IntegerType>(CastDstTy)) {
11756 if (isa<PointerType>(SIOp0->getType()))
11757 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011758 }
Chris Lattner3914f722009-01-24 01:00:13 +000011759
11760 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11761 // emit a GEP to index into its first field.
11762 if (!NewGEPIndices.empty()) {
11763 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011764 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011765 NewGEPIndices.size());
11766 else
11767 CastOp = IC.InsertNewInstBefore(
11768 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11769 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011770 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011771 }
11772
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011773 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011774 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011775 else
11776 NewCast = IC.InsertNewInstBefore(
11777 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11778 SI);
11779 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011780}
11781
Chris Lattner4aebaee2008-11-27 08:56:30 +000011782/// equivalentAddressValues - Test if A and B will obviously have the same
11783/// value. This includes recognizing that %t0 and %t1 will have the same
11784/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011785/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011786/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011787/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011788/// %t2 = load i32* %t1
11789///
11790static bool equivalentAddressValues(Value *A, Value *B) {
11791 // Test if the values are trivially equivalent.
11792 if (A == B) return true;
11793
11794 // Test if the values come form identical arithmetic instructions.
11795 if (isa<BinaryOperator>(A) ||
11796 isa<CastInst>(A) ||
11797 isa<PHINode>(A) ||
11798 isa<GetElementPtrInst>(A))
11799 if (Instruction *BI = dyn_cast<Instruction>(B))
11800 if (cast<Instruction>(A)->isIdenticalTo(BI))
11801 return true;
11802
11803 // Otherwise they may not be equivalent.
11804 return false;
11805}
11806
Dale Johannesen4945c652009-03-03 21:26:39 +000011807// If this instruction has two uses, one of which is a llvm.dbg.declare,
11808// return the llvm.dbg.declare.
11809DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11810 if (!V->hasNUses(2))
11811 return 0;
11812 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11813 UI != E; ++UI) {
11814 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11815 return DI;
11816 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11817 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11818 return DI;
11819 }
11820 }
11821 return 0;
11822}
11823
Chris Lattner2f503e62005-01-31 05:36:43 +000011824Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11825 Value *Val = SI.getOperand(0);
11826 Value *Ptr = SI.getOperand(1);
11827
11828 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011829 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011830 ++NumCombined;
11831 return 0;
11832 }
Chris Lattner836692d2007-01-15 06:51:56 +000011833
11834 // If the RHS is an alloca with a single use, zapify the store, making the
11835 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011836 // If the RHS is an alloca with a two uses, the other one being a
11837 // llvm.dbg.declare, zapify the store and the declare, making the
11838 // alloca dead. We must do this to prevent declare's from affecting
11839 // codegen.
11840 if (!SI.isVolatile()) {
11841 if (Ptr->hasOneUse()) {
11842 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011843 EraseInstFromFunction(SI);
11844 ++NumCombined;
11845 return 0;
11846 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011847 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11848 if (isa<AllocaInst>(GEP->getOperand(0))) {
11849 if (GEP->getOperand(0)->hasOneUse()) {
11850 EraseInstFromFunction(SI);
11851 ++NumCombined;
11852 return 0;
11853 }
11854 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11855 EraseInstFromFunction(*DI);
11856 EraseInstFromFunction(SI);
11857 ++NumCombined;
11858 return 0;
11859 }
11860 }
11861 }
11862 }
11863 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11864 EraseInstFromFunction(*DI);
11865 EraseInstFromFunction(SI);
11866 ++NumCombined;
11867 return 0;
11868 }
Chris Lattner836692d2007-01-15 06:51:56 +000011869 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011870
Dan Gohman9941f742007-07-20 16:34:21 +000011871 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011872 if (TD) {
11873 unsigned KnownAlign =
11874 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11875 if (KnownAlign >
11876 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11877 SI.getAlignment()))
11878 SI.setAlignment(KnownAlign);
11879 }
Dan Gohman9941f742007-07-20 16:34:21 +000011880
Dale Johannesenacb51a32009-03-03 01:43:03 +000011881 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011882 // stores to the same location, separated by a few arithmetic operations. This
11883 // situation often occurs with bitfield accesses.
11884 BasicBlock::iterator BBI = &SI;
11885 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11886 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011887 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011888 // Don't count debug info directives, lest they affect codegen,
11889 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11890 // It is necessary for correctness to skip those that feed into a
11891 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011892 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011893 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011894 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011895 continue;
11896 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011897
11898 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11899 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011900 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11901 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011902 ++NumDeadStore;
11903 ++BBI;
11904 EraseInstFromFunction(*PrevSI);
11905 continue;
11906 }
11907 break;
11908 }
11909
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011910 // If this is a load, we have to stop. However, if the loaded value is from
11911 // the pointer we're loading and is producing the pointer we're storing,
11912 // then *this* store is dead (X = load P; store X -> P).
11913 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011914 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11915 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011916 EraseInstFromFunction(SI);
11917 ++NumCombined;
11918 return 0;
11919 }
11920 // Otherwise, this is a load from some other location. Stores before it
11921 // may not be dead.
11922 break;
11923 }
11924
Chris Lattner9ca96412006-02-08 03:25:32 +000011925 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011926 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011927 break;
11928 }
11929
11930
11931 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011932
11933 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011934 if (isa<ConstantPointerNull>(Ptr) &&
11935 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011936 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011937 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011938 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011939 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011940 ++NumCombined;
11941 }
11942 return 0; // Do not modify these!
11943 }
11944
11945 // store undef, Ptr -> noop
11946 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011947 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011948 ++NumCombined;
11949 return 0;
11950 }
11951
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011952 // If the pointer destination is a cast, see if we can fold the cast into the
11953 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011954 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011955 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11956 return Res;
11957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011958 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011959 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11960 return Res;
11961
Chris Lattner408902b2005-09-12 23:23:25 +000011962
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011963 // If this store is the last instruction in the basic block (possibly
11964 // excepting debug info instructions and the pointer bitcasts that feed
11965 // into them), and if the block ends with an unconditional branch, try
11966 // to move it to the successor block.
11967 BBI = &SI;
11968 do {
11969 ++BBI;
11970 } while (isa<DbgInfoIntrinsic>(BBI) ||
11971 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011972 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973 if (BI->isUnconditional())
11974 if (SimplifyStoreAtEndOfBlock(SI))
11975 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011976
Chris Lattner2f503e62005-01-31 05:36:43 +000011977 return 0;
11978}
11979
Chris Lattner3284d1f2007-04-15 00:07:55 +000011980/// SimplifyStoreAtEndOfBlock - Turn things like:
11981/// if () { *P = v1; } else { *P = v2 }
11982/// into a phi node with a store in the successor.
11983///
Chris Lattner31755a02007-04-15 01:02:18 +000011984/// Simplify things like:
11985/// *P = v1; if () { *P = v2; }
11986/// into a phi node with a store in the successor.
11987///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11989 BasicBlock *StoreBB = SI.getParent();
11990
11991 // Check to see if the successor block has exactly two incoming edges. If
11992 // so, see if the other predecessor contains a store to the same location.
11993 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011994 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011995
11996 // Determine whether Dest has exactly two predecessors and, if so, compute
11997 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011998 pred_iterator PI = pred_begin(DestBB);
11999 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012000 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012001 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012002 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012003 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012004 return false;
12005
12006 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012007 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012008 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012009 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012010 }
Chris Lattner31755a02007-04-15 01:02:18 +000012011 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012012 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012013
12014 // Bail out if all the relevant blocks aren't distinct (this can happen,
12015 // for example, if SI is in an infinite loop)
12016 if (StoreBB == DestBB || OtherBB == DestBB)
12017 return false;
12018
Chris Lattner31755a02007-04-15 01:02:18 +000012019 // Verify that the other block ends in a branch and is not otherwise empty.
12020 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012022 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012023 return false;
12024
Chris Lattner31755a02007-04-15 01:02:18 +000012025 // If the other block ends in an unconditional branch, check for the 'if then
12026 // else' case. there is an instruction before the branch.
12027 StoreInst *OtherStore = 0;
12028 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012029 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012030 // Skip over debugging info.
12031 while (isa<DbgInfoIntrinsic>(BBI) ||
12032 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12033 if (BBI==OtherBB->begin())
12034 return false;
12035 --BBI;
12036 }
12037 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012038 OtherStore = dyn_cast<StoreInst>(BBI);
12039 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12040 return false;
12041 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012042 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012043 // destinations is StoreBB, then we have the if/then case.
12044 if (OtherBr->getSuccessor(0) != StoreBB &&
12045 OtherBr->getSuccessor(1) != StoreBB)
12046 return false;
12047
12048 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012049 // if/then triangle. See if there is a store to the same ptr as SI that
12050 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012051 for (;; --BBI) {
12052 // Check to see if we find the matching store.
12053 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12054 if (OtherStore->getOperand(1) != SI.getOperand(1))
12055 return false;
12056 break;
12057 }
Eli Friedman6903a242008-06-13 22:02:12 +000012058 // If we find something that may be using or overwriting the stored
12059 // value, or if we run out of instructions, we can't do the xform.
12060 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012061 BBI == OtherBB->begin())
12062 return false;
12063 }
12064
12065 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012066 // make sure nothing reads or overwrites the stored value in
12067 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012068 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12069 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012070 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012071 return false;
12072 }
12073 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012074
Chris Lattner31755a02007-04-15 01:02:18 +000012075 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012076 Value *MergedVal = OtherStore->getOperand(0);
12077 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012078 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012079 PN->reserveOperandSpace(2);
12080 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012081 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12082 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012083 }
12084
12085 // Advance to a place where it is safe to insert the new store and
12086 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012087 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012088 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12089 OtherStore->isVolatile()), *BBI);
12090
12091 // Nuke the old stores.
12092 EraseInstFromFunction(SI);
12093 EraseInstFromFunction(*OtherStore);
12094 ++NumCombined;
12095 return true;
12096}
12097
Chris Lattner2f503e62005-01-31 05:36:43 +000012098
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012099Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12100 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012101 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012102 BasicBlock *TrueDest;
12103 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012104 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012105 !isa<Constant>(X)) {
12106 // Swap Destinations and condition...
12107 BI.setCondition(X);
12108 BI.setSuccessor(0, FalseDest);
12109 BI.setSuccessor(1, TrueDest);
12110 return &BI;
12111 }
12112
Reid Spencere4d87aa2006-12-23 06:05:41 +000012113 // Cannonicalize fcmp_one -> fcmp_oeq
12114 FCmpInst::Predicate FPred; Value *Y;
12115 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Dan Gohman4ae51262009-08-12 16:23:25 +000012116 TrueDest, FalseDest)))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012117 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12118 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12119 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012120 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012121 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012122 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012123 // Swap Destinations and condition...
12124 BI.setCondition(NewSCC);
12125 BI.setSuccessor(0, FalseDest);
12126 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012127 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012128 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012129 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012130 return &BI;
12131 }
12132
12133 // Cannonicalize icmp_ne -> icmp_eq
12134 ICmpInst::Predicate IPred;
12135 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Dan Gohman4ae51262009-08-12 16:23:25 +000012136 TrueDest, FalseDest)))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012137 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12138 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12139 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12140 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012141 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012142 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012143 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012144 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012145 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012146 BI.setSuccessor(0, FalseDest);
12147 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012148 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012149 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012150 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012151 return &BI;
12152 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012153
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012154 return 0;
12155}
Chris Lattner0864acf2002-11-04 16:18:53 +000012156
Chris Lattner46238a62004-07-03 00:26:11 +000012157Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12158 Value *Cond = SI.getCondition();
12159 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12160 if (I->getOpcode() == Instruction::Add)
12161 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12162 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12163 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012164 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012165 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012166 AddRHS));
12167 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012168 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012169 return &SI;
12170 }
12171 }
12172 return 0;
12173}
12174
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012175Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012176 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012177
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012178 if (!EV.hasIndices())
12179 return ReplaceInstUsesWith(EV, Agg);
12180
12181 if (Constant *C = dyn_cast<Constant>(Agg)) {
12182 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012183 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012184
12185 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012186 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012187
12188 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12189 // Extract the element indexed by the first index out of the constant
12190 Value *V = C->getOperand(*EV.idx_begin());
12191 if (EV.getNumIndices() > 1)
12192 // Extract the remaining indices out of the constant indexed by the
12193 // first index
12194 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12195 else
12196 return ReplaceInstUsesWith(EV, V);
12197 }
12198 return 0; // Can't handle other constants
12199 }
12200 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12201 // We're extracting from an insertvalue instruction, compare the indices
12202 const unsigned *exti, *exte, *insi, *inse;
12203 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12204 exte = EV.idx_end(), inse = IV->idx_end();
12205 exti != exte && insi != inse;
12206 ++exti, ++insi) {
12207 if (*insi != *exti)
12208 // The insert and extract both reference distinctly different elements.
12209 // This means the extract is not influenced by the insert, and we can
12210 // replace the aggregate operand of the extract with the aggregate
12211 // operand of the insert. i.e., replace
12212 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12213 // %E = extractvalue { i32, { i32 } } %I, 0
12214 // with
12215 // %E = extractvalue { i32, { i32 } } %A, 0
12216 return ExtractValueInst::Create(IV->getAggregateOperand(),
12217 EV.idx_begin(), EV.idx_end());
12218 }
12219 if (exti == exte && insi == inse)
12220 // Both iterators are at the end: Index lists are identical. Replace
12221 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12222 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12223 // with "i32 42"
12224 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12225 if (exti == exte) {
12226 // The extract list is a prefix of the insert list. i.e. replace
12227 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12228 // %E = extractvalue { i32, { i32 } } %I, 1
12229 // with
12230 // %X = extractvalue { i32, { i32 } } %A, 1
12231 // %E = insertvalue { i32 } %X, i32 42, 0
12232 // by switching the order of the insert and extract (though the
12233 // insertvalue should be left in, since it may have other uses).
12234 Value *NewEV = InsertNewInstBefore(
12235 ExtractValueInst::Create(IV->getAggregateOperand(),
12236 EV.idx_begin(), EV.idx_end()),
12237 EV);
12238 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12239 insi, inse);
12240 }
12241 if (insi == inse)
12242 // The insert list is a prefix of the extract list
12243 // We can simply remove the common indices from the extract and make it
12244 // operate on the inserted value instead of the insertvalue result.
12245 // i.e., replace
12246 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12247 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12248 // with
12249 // %E extractvalue { i32 } { i32 42 }, 0
12250 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12251 exti, exte);
12252 }
12253 // Can't simplify extracts from other values. Note that nested extracts are
12254 // already simplified implicitely by the above (extract ( extract (insert) )
12255 // will be translated into extract ( insert ( extract ) ) first and then just
12256 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012257 return 0;
12258}
12259
Chris Lattner220b0cf2006-03-05 00:22:33 +000012260/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12261/// is to leave as a vector operation.
12262static bool CheapToScalarize(Value *V, bool isConstant) {
12263 if (isa<ConstantAggregateZero>(V))
12264 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012265 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012266 if (isConstant) return true;
12267 // If all elts are the same, we can extract.
12268 Constant *Op0 = C->getOperand(0);
12269 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12270 if (C->getOperand(i) != Op0)
12271 return false;
12272 return true;
12273 }
12274 Instruction *I = dyn_cast<Instruction>(V);
12275 if (!I) return false;
12276
12277 // Insert element gets simplified to the inserted element or is deleted if
12278 // this is constant idx extract element and its a constant idx insertelt.
12279 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12280 isa<ConstantInt>(I->getOperand(2)))
12281 return true;
12282 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12283 return true;
12284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12285 if (BO->hasOneUse() &&
12286 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12287 CheapToScalarize(BO->getOperand(1), isConstant)))
12288 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012289 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12290 if (CI->hasOneUse() &&
12291 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12292 CheapToScalarize(CI->getOperand(1), isConstant)))
12293 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012294
12295 return false;
12296}
12297
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012298/// Read and decode a shufflevector mask.
12299///
12300/// It turns undef elements into values that are larger than the number of
12301/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012302static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12303 unsigned NElts = SVI->getType()->getNumElements();
12304 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12305 return std::vector<unsigned>(NElts, 0);
12306 if (isa<UndefValue>(SVI->getOperand(2)))
12307 return std::vector<unsigned>(NElts, 2*NElts);
12308
12309 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012310 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012311 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12312 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012313 Result.push_back(NElts*2); // undef -> 8
12314 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012315 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012316 return Result;
12317}
12318
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012319/// FindScalarElement - Given a vector and an element number, see if the scalar
12320/// value is already around as a register, for example if it were inserted then
12321/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012322static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012323 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012324 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12325 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012326 unsigned Width = PTy->getNumElements();
12327 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012328 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012329
12330 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012331 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012332 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012333 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012334 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012335 return CP->getOperand(EltNo);
12336 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12337 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012338 if (!isa<ConstantInt>(III->getOperand(2)))
12339 return 0;
12340 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012341
12342 // If this is an insert to the element we are looking for, return the
12343 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012344 if (EltNo == IIElt)
12345 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012346
12347 // Otherwise, the insertelement doesn't modify the value, recurse on its
12348 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012349 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012350 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012351 unsigned LHSWidth =
12352 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012353 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012354 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012355 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012356 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012357 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012358 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012359 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012360 }
12361
12362 // Otherwise, we don't know.
12363 return 0;
12364}
12365
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012366Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012367 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012368 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012369 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012370
Dan Gohman07a96762007-07-16 14:29:03 +000012371 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012372 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012373 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012374
Reid Spencer9d6565a2007-02-15 02:26:10 +000012375 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012376 // If vector val is constant with all elements the same, replace EI with
12377 // that element. When the elements are not identical, we cannot replace yet
12378 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012379 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012380 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012381 if (C->getOperand(i) != op0) {
12382 op0 = 0;
12383 break;
12384 }
12385 if (op0)
12386 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012387 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012388
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012389 // If extracting a specified index from the vector, see if we can recursively
12390 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012391 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012392 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012393 unsigned VectorWidth =
12394 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012395
12396 // If this is extracting an invalid index, turn this into undef, to avoid
12397 // crashing the code below.
12398 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012399 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012400
Chris Lattner867b99f2006-10-05 06:55:50 +000012401 // This instruction only demands the single element from the input vector.
12402 // If the input vector has a single use, simplify it based on this use
12403 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012404 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012405 APInt UndefElts(VectorWidth, 0);
12406 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012407 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012408 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012409 EI.setOperand(0, V);
12410 return &EI;
12411 }
12412 }
12413
Owen Andersond672ecb2009-07-03 00:17:18 +000012414 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012415 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012416
12417 // If the this extractelement is directly using a bitcast from a vector of
12418 // the same number of elements, see if we can find the source element from
12419 // it. In this case, we will end up needing to bitcast the scalars.
12420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12421 if (const VectorType *VT =
12422 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12423 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012424 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12425 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012426 return new BitCastInst(Elt, EI.getType());
12427 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012428 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012429
Chris Lattner73fa49d2006-05-25 22:53:38 +000012430 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012431 if (I->hasOneUse()) {
12432 // Push extractelement into predecessor operation if legal and
12433 // profitable to do so
12434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012435 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12436 if (CheapToScalarize(BO, isConstantElt)) {
12437 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012438 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012439 EI.getName()+".lhs");
12440 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012441 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012442 EI.getName()+".rhs");
12443 InsertNewInstBefore(newEI0, EI);
12444 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012445 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012446 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012447 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012448 unsigned AS =
12449 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012450 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersondebcb012009-07-29 22:17:13 +000012451 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012452 GetElementPtrInst *GEP =
12453 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012454 cast<GEPOperator>(GEP)->setIsInBounds(true);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012455 InsertNewInstBefore(GEP, EI);
12456 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012457 }
12458 }
12459 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12460 // Extracting the inserted element?
12461 if (IE->getOperand(2) == EI.getOperand(1))
12462 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12463 // If the inserted and extracted elements are constants, they must not
12464 // be the same value, extract from the pre-inserted value instead.
12465 if (isa<Constant>(IE->getOperand(2)) &&
12466 isa<Constant>(EI.getOperand(1))) {
12467 AddUsesToWorkList(EI);
12468 EI.setOperand(0, IE->getOperand(0));
12469 return &EI;
12470 }
12471 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12472 // If this is extracting an element from a shufflevector, figure out where
12473 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012474 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12475 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012476 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012477 unsigned LHSWidth =
12478 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12479
12480 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012481 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012482 else if (SrcIdx < LHSWidth*2) {
12483 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012484 Src = SVI->getOperand(1);
12485 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012486 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012487 }
Eric Christophera3500da2009-07-25 02:28:41 +000012488 return ExtractElementInst::Create(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +000012489 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012490 }
12491 }
Eli Friedman2451a642009-07-18 23:06:53 +000012492 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012493 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012494 return 0;
12495}
12496
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012497/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12498/// elements from either LHS or RHS, return the shuffle mask and true.
12499/// Otherwise, return false.
12500static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012501 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012502 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012503 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12504 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012505 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012506
12507 if (isa<UndefValue>(V)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012508 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012509 return true;
12510 } else if (V == LHS) {
12511 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012512 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012513 return true;
12514 } else if (V == RHS) {
12515 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012516 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012517 return true;
12518 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12519 // If this is an insert of an extract from some other vector, include it.
12520 Value *VecOp = IEI->getOperand(0);
12521 Value *ScalarOp = IEI->getOperand(1);
12522 Value *IdxOp = IEI->getOperand(2);
12523
Chris Lattnerd929f062006-04-27 21:14:21 +000012524 if (!isa<ConstantInt>(IdxOp))
12525 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012526 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012527
12528 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12529 // Okay, we can handle this if the vector we are insertinting into is
12530 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012531 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012532 // If so, update the mask to reflect the inserted undef.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012533 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012534 return true;
12535 }
12536 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12537 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012538 EI->getOperand(0)->getType() == V->getType()) {
12539 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012540 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012541
12542 // This must be extracting from either LHS or RHS.
12543 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12544 // Okay, we can handle this if the vector we are insertinting into is
12545 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012546 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012547 // If so, update the mask to reflect the inserted value.
12548 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012549 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012550 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012551 } else {
12552 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012553 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012554 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012555
12556 }
12557 return true;
12558 }
12559 }
12560 }
12561 }
12562 }
12563 // TODO: Handle shufflevector here!
12564
12565 return false;
12566}
12567
12568/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12569/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12570/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012571static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012572 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012573 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012574 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012575 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012576 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012577
12578 if (isa<UndefValue>(V)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012579 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012580 return V;
12581 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012582 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012583 return V;
12584 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12585 // If this is an insert of an extract from some other vector, include it.
12586 Value *VecOp = IEI->getOperand(0);
12587 Value *ScalarOp = IEI->getOperand(1);
12588 Value *IdxOp = IEI->getOperand(2);
12589
12590 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12591 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12592 EI->getOperand(0)->getType() == V->getType()) {
12593 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012594 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12595 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012596
12597 // Either the extracted from or inserted into vector must be RHSVec,
12598 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012599 if (EI->getOperand(0) == RHS || RHS == 0) {
12600 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012601 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012602 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012603 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012604 return V;
12605 }
12606
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012607 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012608 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12609 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012610 // Everything but the extracted element is replaced with the RHS.
12611 for (unsigned i = 0; i != NumElts; ++i) {
12612 if (i != InsertedIdx)
Owen Andersoneed707b2009-07-24 23:12:02 +000012613 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012614 }
12615 return V;
12616 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012617
12618 // If this insertelement is a chain that comes from exactly these two
12619 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012620 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12621 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012622 return EI->getOperand(0);
12623
Chris Lattnerefb47352006-04-15 01:39:45 +000012624 }
12625 }
12626 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012627 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012628
12629 // Otherwise, can't do anything fancy. Return an identity vector.
12630 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012631 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012632 return V;
12633}
12634
12635Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12636 Value *VecOp = IE.getOperand(0);
12637 Value *ScalarOp = IE.getOperand(1);
12638 Value *IdxOp = IE.getOperand(2);
12639
Chris Lattner599ded12007-04-09 01:11:16 +000012640 // Inserting an undef or into an undefined place, remove this.
12641 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12642 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012643
Chris Lattnerefb47352006-04-15 01:39:45 +000012644 // If the inserted element was extracted from some other vector, and if the
12645 // indexes are constant, try to turn this into a shufflevector operation.
12646 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12647 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12648 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012649 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012650 unsigned ExtractedIdx =
12651 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012652 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012653
12654 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12655 return ReplaceInstUsesWith(IE, VecOp);
12656
12657 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012658 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012659
12660 // If we are extracting a value from a vector, then inserting it right
12661 // back into the same place, just use the input vector.
12662 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12663 return ReplaceInstUsesWith(IE, VecOp);
12664
12665 // We could theoretically do this for ANY input. However, doing so could
12666 // turn chains of insertelement instructions into a chain of shufflevector
12667 // instructions, and right now we do not merge shufflevectors. As such,
12668 // only do this in a situation where it is clear that there is benefit.
12669 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12670 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12671 // the values of VecOp, except then one read from EIOp0.
12672 // Build a new shuffle mask.
12673 std::vector<Constant*> Mask;
12674 if (isa<UndefValue>(VecOp))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012675 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012676 else {
12677 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneed707b2009-07-24 23:12:02 +000012678 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012679 NumVectorElts));
12680 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012681 Mask[InsertedIdx] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012682 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012683 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012684 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012685 }
12686
12687 // If this insertelement isn't used by some other insertelement, turn it
12688 // (and any insertelements it points to), into one big shuffle.
12689 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12690 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012691 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012692 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012693 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012694 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012695 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012696 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012697 }
12698 }
12699 }
12700
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012701 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12702 APInt UndefElts(VWidth, 0);
12703 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12704 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12705 return &IE;
12706
Chris Lattnerefb47352006-04-15 01:39:45 +000012707 return 0;
12708}
12709
12710
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012711Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12712 Value *LHS = SVI.getOperand(0);
12713 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012714 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012715
12716 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012717
Chris Lattner867b99f2006-10-05 06:55:50 +000012718 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012719 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012720 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012721
Dan Gohman488fbfc2008-09-09 18:11:14 +000012722 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012723
12724 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12725 return 0;
12726
Evan Cheng388df622009-02-03 10:05:09 +000012727 APInt UndefElts(VWidth, 0);
12728 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12729 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012730 LHS = SVI.getOperand(0);
12731 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012732 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012733 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012734
Chris Lattner863bcff2006-05-25 23:48:38 +000012735 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12736 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12737 if (LHS == RHS || isa<UndefValue>(LHS)) {
12738 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012739 // shuffle(undef,undef,mask) -> undef.
12740 return ReplaceInstUsesWith(SVI, LHS);
12741 }
12742
Chris Lattner863bcff2006-05-25 23:48:38 +000012743 // Remap any references to RHS to use LHS.
12744 std::vector<Constant*> Elts;
12745 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012746 if (Mask[i] >= 2*e)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012747 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012748 else {
12749 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012750 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012751 Mask[i] = 2*e; // Turn into undef.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012752 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012753 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012754 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneed707b2009-07-24 23:12:02 +000012755 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012756 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012757 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012758 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012759 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012760 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012761 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012762 LHS = SVI.getOperand(0);
12763 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012764 MadeChange = true;
12765 }
12766
Chris Lattner7b2e27922006-05-26 00:29:06 +000012767 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012768 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012769
Chris Lattner863bcff2006-05-25 23:48:38 +000012770 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12771 if (Mask[i] >= e*2) continue; // Ignore undef values.
12772 // Is this an identity shuffle of the LHS value?
12773 isLHSID &= (Mask[i] == i);
12774
12775 // Is this an identity shuffle of the RHS value?
12776 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012777 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012778
Chris Lattner863bcff2006-05-25 23:48:38 +000012779 // Eliminate identity shuffles.
12780 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12781 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012782
Chris Lattner7b2e27922006-05-26 00:29:06 +000012783 // If the LHS is a shufflevector itself, see if we can combine it with this
12784 // one without producing an unusual shuffle. Here we are really conservative:
12785 // we are absolutely afraid of producing a shuffle mask not in the input
12786 // program, because the code gen may not be smart enough to turn a merged
12787 // shuffle into two specific shuffles: it may produce worse code. As such,
12788 // we only merge two shuffles if the result is one of the two input shuffle
12789 // masks. In this case, merging the shuffles just removes one instruction,
12790 // which we know is safe. This is good for things like turning:
12791 // (splat(splat)) -> splat.
12792 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12793 if (isa<UndefValue>(RHS)) {
12794 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12795
12796 std::vector<unsigned> NewMask;
12797 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12798 if (Mask[i] >= 2*e)
12799 NewMask.push_back(2*e);
12800 else
12801 NewMask.push_back(LHSMask[Mask[i]]);
12802
12803 // If the result mask is equal to the src shuffle or this shuffle mask, do
12804 // the replacement.
12805 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012806 unsigned LHSInNElts =
12807 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012808 std::vector<Constant*> Elts;
12809 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012810 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012811 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012812 } else {
Owen Andersoneed707b2009-07-24 23:12:02 +000012813 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012814 }
12815 }
12816 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12817 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012818 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012819 }
12820 }
12821 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012822
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012823 return MadeChange ? &SVI : 0;
12824}
12825
12826
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012827
Chris Lattnerea1c4542004-12-08 23:43:58 +000012828
12829/// TryToSinkInstruction - Try to move the specified instruction from its
12830/// current block into the beginning of DestBlock, which can only happen if it's
12831/// safe to move the instruction past all of the instructions between it and the
12832/// end of its block.
12833static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12834 assert(I->hasOneUse() && "Invariants didn't hold!");
12835
Chris Lattner108e9022005-10-27 17:13:11 +000012836 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012837 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012838 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012839
Chris Lattnerea1c4542004-12-08 23:43:58 +000012840 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012841 if (isa<AllocaInst>(I) && I->getParent() ==
12842 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012843 return false;
12844
Chris Lattner96a52a62004-12-09 07:14:34 +000012845 // We can only sink load instructions if there is nothing between the load and
12846 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012847 if (I->mayReadFromMemory()) {
12848 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012849 Scan != E; ++Scan)
12850 if (Scan->mayWriteToMemory())
12851 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012852 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012853
Dan Gohman02dea8b2008-05-23 21:05:58 +000012854 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012855
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012856 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012857 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012858 ++NumSunkInst;
12859 return true;
12860}
12861
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012862
12863/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12864/// all reachable code to the worklist.
12865///
12866/// This has a couple of tricks to make the code faster and more powerful. In
12867/// particular, we constant fold and DCE instructions as we go, to avoid adding
12868/// them to the worklist (this significantly speeds up instcombine on code where
12869/// many instructions are dead or constant). Additionally, if we find a branch
12870/// whose condition is a known constant, we only visit the reachable successors.
12871///
12872static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012873 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012874 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012875 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012876 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012877 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012878
Chris Lattner2c7718a2007-03-23 19:17:18 +000012879 while (!Worklist.empty()) {
12880 BB = Worklist.back();
12881 Worklist.pop_back();
12882
12883 // We have now visited this block! If we've already been here, ignore it.
12884 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012885
12886 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012887 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12888 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012889
Chris Lattner2c7718a2007-03-23 19:17:18 +000012890 // DCE instruction if trivially dead.
12891 if (isInstructionTriviallyDead(Inst)) {
12892 ++NumDeadInst;
Dan Gohman2df6e642009-08-12 16:28:31 +000012893 DOUT << "IC: DCE: " << *Inst << '\n';
Chris Lattner2c7718a2007-03-23 19:17:18 +000012894 Inst->eraseFromParent();
12895 continue;
12896 }
12897
12898 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012899 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Dan Gohman2df6e642009-08-12 16:28:31 +000012900 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst << '\n';
Chris Lattner2c7718a2007-03-23 19:17:18 +000012901 Inst->replaceAllUsesWith(C);
12902 ++NumConstProp;
12903 Inst->eraseFromParent();
12904 continue;
12905 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012906
Devang Patel7fe1dec2008-11-19 18:56:50 +000012907 // If there are two consecutive llvm.dbg.stoppoint calls then
12908 // it is likely that the optimizer deleted code in between these
12909 // two intrinsics.
12910 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12911 if (DBI_Next) {
12912 if (DBI_Prev
12913 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12914 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12915 IC.RemoveFromWorkList(DBI_Prev);
12916 DBI_Prev->eraseFromParent();
12917 }
12918 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012919 } else {
12920 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012921 }
12922
Chris Lattner2c7718a2007-03-23 19:17:18 +000012923 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012924 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012925
12926 // Recursively visit successors. If this is a branch or switch on a
12927 // constant, only visit the reachable successor.
12928 TerminatorInst *TI = BB->getTerminator();
12929 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12930 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12931 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012932 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012933 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012934 continue;
12935 }
12936 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12937 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12938 // See if this is an explicit destination.
12939 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12940 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012941 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012942 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012943 continue;
12944 }
12945
12946 // Otherwise it is the default destination.
12947 Worklist.push_back(SI->getSuccessor(0));
12948 continue;
12949 }
12950 }
12951
12952 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12953 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012954 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012955}
12956
Chris Lattnerec9c3582007-03-03 02:04:50 +000012957bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012958 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012959 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012960
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012961 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12962 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012963
Chris Lattnerb3d59702005-07-07 20:40:38 +000012964 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012965 // Do a depth-first traversal of the function, populate the worklist with
12966 // the reachable instructions. Ignore blocks that are not reachable. Keep
12967 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012968 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012969 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012970
Chris Lattnerb3d59702005-07-07 20:40:38 +000012971 // Do a quick scan over the function. If we find any blocks that are
12972 // unreachable, remove any instructions inside of them. This prevents
12973 // the instcombine code from having to deal with some bad special cases.
12974 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12975 if (!Visited.count(BB)) {
12976 Instruction *Term = BB->getTerminator();
12977 while (Term != BB->begin()) { // Remove instrs bottom-up
12978 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012979
Dan Gohman2df6e642009-08-12 16:28:31 +000012980 DOUT << "IC: DCE: " << *I << '\n';
Dale Johannesenff278b12009-03-10 21:19:49 +000012981 // A debug intrinsic shouldn't force another iteration if we weren't
12982 // going to do one without it.
12983 if (!isa<DbgInfoIntrinsic>(I)) {
12984 ++NumDeadInst;
12985 Changed = true;
12986 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012987 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012988 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012989 I->eraseFromParent();
12990 }
12991 }
12992 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012993
Chris Lattnerdbab3862007-03-02 21:28:56 +000012994 while (!Worklist.empty()) {
12995 Instruction *I = RemoveOneFromWorkList();
12996 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012997
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012998 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012999 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013000 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000013001 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013002 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000013003 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013004
Dan Gohman2df6e642009-08-12 16:28:31 +000013005 DOUT << "IC: DCE: " << *I << '\n';
Chris Lattnerad5fec12005-01-28 19:32:01 +000013006
13007 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013008 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013009 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013010 continue;
13011 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013012
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013013 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013014 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Dan Gohman2df6e642009-08-12 16:28:31 +000013015 DOUT << "IC: ConstFold to: " << *C << " from: " << *I << '\n';
Chris Lattnerad5fec12005-01-28 19:32:01 +000013016
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013017 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013018 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013019 ReplaceInstUsesWith(*I, C);
13020
Chris Lattner62b14df2002-09-02 04:59:56 +000013021 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013022 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013023 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013024 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013025 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013026 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013027
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013028 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013029 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013030 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13031 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013032 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13033 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013034 if (NewC != CE) {
13035 i->set(NewC);
13036 Changed = true;
13037 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013038 }
13039
Chris Lattnerea1c4542004-12-08 23:43:58 +000013040 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013041 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013042 BasicBlock *BB = I->getParent();
13043 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13044 if (UserParent != BB) {
13045 bool UserIsSuccessor = false;
13046 // See if the user is one of our successors.
13047 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13048 if (*SI == UserParent) {
13049 UserIsSuccessor = true;
13050 break;
13051 }
13052
13053 // If the user is one of our immediate successors, and if that successor
13054 // only has us as a predecessors (we'd have to split the critical edge
13055 // otherwise), we can keep going.
13056 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13057 next(pred_begin(UserParent)) == pred_end(UserParent))
13058 // Okay, the CFG is simple enough, try to sink this instruction.
13059 Changed |= TryToSinkInstruction(I, UserParent);
13060 }
13061 }
13062
Chris Lattner8a2a3112001-12-14 16:52:21 +000013063 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013064#ifndef NDEBUG
13065 std::string OrigI;
13066#endif
13067 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013068 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013069 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013070 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013071 if (Result != I) {
Dan Gohman2df6e642009-08-12 16:28:31 +000013072 DOUT << "IC: Old = " << *I << '\n'
13073 << " New = " << *Result << '\n';
Chris Lattner0cea42a2004-03-13 23:54:27 +000013074
Chris Lattnerf523d062004-06-09 05:08:07 +000013075 // Everything uses the new instruction now.
13076 I->replaceAllUsesWith(Result);
13077
13078 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013079 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013080 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013081
Chris Lattner6934a042007-02-11 01:23:03 +000013082 // Move the name to the new instruction first.
13083 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013084
13085 // Insert the new instruction into the basic block...
13086 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013087 BasicBlock::iterator InsertPos = I;
13088
13089 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13090 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13091 ++InsertPos;
13092
13093 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013094
Chris Lattner00d51312004-05-01 23:27:23 +000013095 // Make sure that we reprocess all operands now that we reduced their
13096 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013097 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013098
Chris Lattnerf523d062004-06-09 05:08:07 +000013099 // Instructions can end up on the worklist more than once. Make sure
13100 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013101 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013102
13103 // Erase the old instruction.
13104 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013105 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013106#ifndef NDEBUG
Dan Gohman2df6e642009-08-12 16:28:31 +000013107 DOUT << "IC: Mod = " << OrigI << '\n'
13108 << " New = " << *I << '\n';
Evan Chengc7baf682007-03-27 16:44:48 +000013109#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013110
Chris Lattner90ac28c2002-08-02 19:29:35 +000013111 // If the instruction was modified, it's possible that it is now dead.
13112 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013113 if (isInstructionTriviallyDead(I)) {
13114 // Make sure we process all operands now that we are reducing their
13115 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013116 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013117
Chris Lattner00d51312004-05-01 23:27:23 +000013118 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013119 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013120 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013121 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013122 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013123 AddToWorkList(I);
13124 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013125 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013126 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013127 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013128 }
13129 }
13130
Chris Lattnerec9c3582007-03-03 02:04:50 +000013131 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013132
13133 // Do an explicit clear, this shrinks the map if needed.
13134 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013135 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013136}
13137
Chris Lattnerec9c3582007-03-03 02:04:50 +000013138
13139bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013140 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013141 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013142
Chris Lattnerec9c3582007-03-03 02:04:50 +000013143 bool EverMadeChange = false;
13144
13145 // Iterate while there is work to do.
13146 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013147 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013148 EverMadeChange = true;
13149 return EverMadeChange;
13150}
13151
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013152FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013153 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013154}