blob: 6163e80221b15ff68ab58bdcbee6bca843cbc981 [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 Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
95 }
96
Chris Lattner7a1e9242009-08-30 06:13:40 +000097 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +000098 void Remove(Instruction *I) {
99 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100 if (It == WorklistMap.end()) return; // Not in worklist.
101
102 // Don't bother moving everything down, just null out the slot.
103 Worklist[It->second] = 0;
104
105 WorklistMap.erase(It);
106 }
107
108 Instruction *RemoveOne() {
109 Instruction *I = Worklist.back();
110 Worklist.pop_back();
111 WorklistMap.erase(I);
112 return I;
113 }
114
115
116 /// Zap - check that the worklist is empty and nuke the backing store for
117 /// the map if it is large.
118 void Zap() {
119 assert(WorklistMap.empty() && "Worklist empty, but map not?");
120
121 // Do an explicit clear, this shrinks the map if needed.
122 WorklistMap.clear();
123 }
124 };
125} // end anonymous namespace.
126
127
128namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +0000129 class VISIBILITY_HIDDEN InstCombiner
130 : public FunctionPass,
131 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000132 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000133 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000134 public:
Chris Lattner7a1e9242009-08-30 06:13:40 +0000135 // Worklist of all of the instructions that need to be simplified.
136 InstCombineWorklist Worklist;
137
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000138 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000139 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000140
Owen Andersone922c022009-07-22 00:24:57 +0000141 LLVMContext *Context;
142 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000143
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000144 /// AddUsersToWorkList - When an instruction is simplified, add all users of
145 /// the instruction to the work lists because they might get more simplified
146 /// now.
147 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000148 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000149 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000150 UI != UE; ++UI)
Chris Lattner7a1e9242009-08-30 06:13:40 +0000151 Worklist.Add(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152 }
153
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000154 /// AddUsesToWorkList - When an instruction is simplified, add operands to
155 /// the work lists because they might get more simplified now.
156 ///
157 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000158 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
159 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattner7a1e9242009-08-30 06:13:40 +0000160 Worklist.Add(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000161 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000162
163 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
164 /// dead. Add all of its operands to the worklist, turning them into
165 /// undef's to reduce the number of uses of those instructions.
166 ///
167 /// Return the specified operand before it is turned into an undef.
168 ///
169 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
170 Value *R = I.getOperand(op);
171
Gabor Greif177dd3f2008-06-12 21:37:33 +0000172 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
173 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +0000174 Worklist.Add(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000175 // Set the operand to undef to drop the use.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000176 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000177 }
178
179 return R;
180 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000181
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000182 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000183 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000184
185 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000186
Chris Lattner97e52e42002-04-28 21:27:06 +0000187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000188 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000189 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000190 }
191
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000192 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000193
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000194 // Visitation implementation - Implement instruction combining for different
195 // instruction types. The semantics are as follows:
196 // Return Value:
197 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000198 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000200 //
Chris Lattner7e708292002-06-25 16:13:24 +0000201 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000202 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000203 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000204 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000205 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000207 Instruction *visitURem(BinaryOperator &I);
208 Instruction *visitSRem(BinaryOperator &I);
209 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000210 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000211 Instruction *commonRemTransforms(BinaryOperator &I);
212 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000213 Instruction *commonDivTransforms(BinaryOperator &I);
214 Instruction *commonIDivTransforms(BinaryOperator &I);
215 Instruction *visitUDiv(BinaryOperator &I);
216 Instruction *visitSDiv(BinaryOperator &I);
217 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000218 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000219 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000221 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000222 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000223 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000224 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000225 Instruction *visitOr (BinaryOperator &I);
226 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000227 Instruction *visitShl(BinaryOperator &I);
228 Instruction *visitAShr(BinaryOperator &I);
229 Instruction *visitLShr(BinaryOperator &I);
230 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000231 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
232 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000233 Instruction *visitFCmpInst(FCmpInst &I);
234 Instruction *visitICmpInst(ICmpInst &I);
235 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000236 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
237 Instruction *LHS,
238 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000239 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000241
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000242 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000243 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000245 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000246 Instruction *commonCastTransforms(CastInst &CI);
247 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000248 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000249 Instruction *visitTrunc(TruncInst &CI);
250 Instruction *visitZExt(ZExtInst &CI);
251 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000252 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000253 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000254 Instruction *visitFPToUI(FPToUIInst &FI);
255 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000256 Instruction *visitUIToFP(CastInst &CI);
257 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000258 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000259 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000260 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000261 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
262 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000263 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000264 Instruction *visitSelectInst(SelectInst &SI);
265 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000266 Instruction *visitCallInst(CallInst &CI);
267 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000268 Instruction *visitPHINode(PHINode &PN);
269 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000270 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000271 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000272 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000273 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000274 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000275 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000276 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000277 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000278 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000279 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000280
281 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000282 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000283
Chris Lattner9fe38862003-06-19 17:00:31 +0000284 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000285 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000286 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000287 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000288 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000290 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000291 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
292
Chris Lattner9fe38862003-06-19 17:00:31 +0000293
Chris Lattner28977af2004-04-05 01:30:19 +0000294 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000295 // InsertNewInstBefore - insert an instruction New before instruction Old
296 // in the program. Add the new instruction to the worklist.
297 //
Chris Lattner955f3312004-09-28 21:48:02 +0000298 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000299 assert(New && New->getParent() == 0 &&
300 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000301 BasicBlock *BB = Old.getParent();
302 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000303 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000304 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000305 }
306
Chris Lattner0c967662004-09-24 15:21:34 +0000307 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
308 /// This also adds the cast to the worklist. Finally, this returns the
309 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000310 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
311 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000312 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000313
Chris Lattnere2ed0572006-04-06 19:19:17 +0000314 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000315 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000316
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000317 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000318 Worklist.Add(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000319 return C;
320 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000321
322 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
323 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
324 }
325
Chris Lattner0c967662004-09-24 15:21:34 +0000326
Chris Lattner8b170942002-08-09 23:47:40 +0000327 // ReplaceInstUsesWith - This method is to be used when an instruction is
328 // found to be dead, replacable with another preexisting expression. Here
329 // we add all uses of I to the worklist, replace all uses of I with the new
330 // value, then return I, so that the inst combiner will know that I was
331 // modified.
332 //
333 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000334 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner7a1e9242009-08-30 06:13:40 +0000335
336 // If we are replacing the instruction with itself, this must be in a
337 // segment of unreachable code, so just clobber the instruction.
338 if (&I == V)
339 V = UndefValue::get(I.getType());
340
341 I.replaceAllUsesWith(V);
342 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
345 // EraseInstFromFunction - When dealing with an instruction that has side
346 // effects or produces a void value, we can't rely on DCE to delete the
347 // instruction. Instead, visit methods should return the value returned by
348 // this function.
349 Instruction *EraseInstFromFunction(Instruction &I) {
350 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000351 // Make sure that we reprocess all operands now that we reduced their
352 // use counts.
353 if (I.getNumOperands() < 8)
354 AddUsesToWorkList(I);
355 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000356 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000357 return 0; // Don't do anything with FI
358 }
Chris Lattner173234a2008-06-02 01:18:21 +0000359
360 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
361 APInt &KnownOne, unsigned Depth = 0) const {
362 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
363 }
364
365 bool MaskedValueIsZero(Value *V, const APInt &Mask,
366 unsigned Depth = 0) const {
367 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
368 }
369 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
370 return llvm::ComputeNumSignBits(Op, TD, Depth);
371 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000372
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000373 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000374
Reid Spencere4d87aa2006-12-23 06:05:41 +0000375 /// SimplifyCommutative - This performs a few simplifications for
376 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000377 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000378
Reid Spencere4d87aa2006-12-23 06:05:41 +0000379 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
380 /// most-complex to least-complex order.
381 bool SimplifyCompare(CmpInst &I);
382
Chris Lattner886ab6c2009-01-31 08:15:18 +0000383 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
384 /// based on the demanded bits.
385 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
386 APInt& KnownZero, APInt& KnownOne,
387 unsigned Depth);
388 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000389 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000390 unsigned Depth=0);
391
392 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
393 /// SimplifyDemandedBits knows about. See if the instruction has any
394 /// properties that allow us to simplify its operands.
395 bool SimplifyDemandedInstructionBits(Instruction &Inst);
396
Evan Cheng388df622009-02-03 10:05:09 +0000397 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
398 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000399
Chris Lattner4e998b22004-09-29 05:07:12 +0000400 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
401 // PHI node as operand #0, see if we can fold the instruction into the PHI
402 // (which is only possible if all operands to the PHI are constants).
403 Instruction *FoldOpIntoPhi(Instruction &I);
404
Chris Lattnerbac32862004-11-14 19:13:23 +0000405 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
406 // operator and they all are only used by the PHI, PHI together their
407 // inputs, and do the operation once, to the result of the PHI.
408 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000409 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000410 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
411
Chris Lattner7da52b22006-11-01 04:51:18 +0000412
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000413 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
414 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000415
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000416 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000417 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000418 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000419 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000420 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000421 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000422 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000423 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000424 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000425
Chris Lattnerafe91a52006-06-15 19:07:26 +0000426
Reid Spencerc55b2432006-12-13 18:21:21 +0000427 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000428
Dan Gohman6de29f82009-06-15 22:12:54 +0000429 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000430 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000431 unsigned GetOrEnforceKnownAlignment(Value *V,
432 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000433
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000434 };
Chris Lattner873ff012009-08-30 05:55:36 +0000435} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000436
Dan Gohman844731a2008-05-13 00:00:25 +0000437char InstCombiner::ID = 0;
438static RegisterPass<InstCombiner>
439X("instcombine", "Combine redundant instructions");
440
Chris Lattner4f98c562003-03-10 21:43:22 +0000441// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000442// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000443static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000444 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000445 if (BinaryOperator::isNeg(V) ||
446 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000447 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000448 return 3;
449 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000450 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000451 if (isa<Argument>(V)) return 3;
452 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000453}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000454
Chris Lattnerc8802d22003-03-11 00:12:48 +0000455// isOnlyUse - Return true if this instruction will be deleted if we stop using
456// it.
457static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000458 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000459}
460
Chris Lattner4cb170c2004-02-23 06:38:22 +0000461// getPromotedType - Return the specified type promoted as it would be to pass
462// though a va_arg area...
463static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000464 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
465 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000466 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000467 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000468 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000469}
470
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000471/// getBitCastOperand - If the specified operand is a CastInst, a constant
472/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
473/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000474static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000475 if (Operator *O = dyn_cast<Operator>(V)) {
476 if (O->getOpcode() == Instruction::BitCast)
477 return O->getOperand(0);
478 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
479 if (GEP->hasAllZeroIndices())
480 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000481 }
Chris Lattnereed48272005-09-13 00:40:14 +0000482 return 0;
483}
484
Reid Spencer3da59db2006-11-27 01:05:10 +0000485/// This function is a wrapper around CastInst::isEliminableCastPair. It
486/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000487static Instruction::CastOps
488isEliminableCastPair(
489 const CastInst *CI, ///< The first cast instruction
490 unsigned opcode, ///< The opcode of the second cast instruction
491 const Type *DstTy, ///< The target type for the second cast instruction
492 TargetData *TD ///< The target data for pointer size
493) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000494
Reid Spencer3da59db2006-11-27 01:05:10 +0000495 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
496 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000497
Reid Spencer3da59db2006-11-27 01:05:10 +0000498 // Get the opcodes of the two Cast instructions
499 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
500 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000501
Chris Lattnera0e69692009-03-24 18:35:40 +0000502 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000503 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000504 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000505
506 // We don't want to form an inttoptr or ptrtoint that converts to an integer
507 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000508 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000509 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000510 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000511 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000512 Res = 0;
513
514 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000515}
516
517/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
518/// in any code being generated. It does not require codegen if V is simple
519/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000520static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
521 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000522 if (V->getType() == Ty || isa<Constant>(V)) return false;
523
Chris Lattner01575b72006-05-25 23:24:33 +0000524 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000525 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000526 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000527 return false;
528 return true;
529}
530
Chris Lattner4f98c562003-03-10 21:43:22 +0000531// SimplifyCommutative - This performs a few simplifications for commutative
532// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000533//
Chris Lattner4f98c562003-03-10 21:43:22 +0000534// 1. Order operands such that they are listed from right (least complex) to
535// left (most complex). This puts constants before unary operators before
536// binary operators.
537//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
539// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000540//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000543 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000545
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 if (!I.isAssociative()) return Changed;
547 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
549 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
550 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000551 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000552 cast<Constant>(I.getOperand(1)),
553 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000554 I.setOperand(0, Op->getOperand(0));
555 I.setOperand(1, Folded);
556 return true;
557 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
558 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
559 isOnlyUse(Op) && isOnlyUse(Op1)) {
560 Constant *C1 = cast<Constant>(Op->getOperand(1));
561 Constant *C2 = cast<Constant>(Op1->getOperand(1));
562
563 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000564 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000565 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566 Op1->getOperand(0),
567 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000568 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 I.setOperand(0, New);
570 I.setOperand(1, Folded);
571 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000572 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000573 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000574 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000575}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000576
Reid Spencere4d87aa2006-12-23 06:05:41 +0000577/// SimplifyCompare - For a CmpInst this function just orders the operands
578/// so that theyare listed from right (least complex) to left (most complex).
579/// This puts constants before unary operators before binary operators.
580bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000581 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000582 return false;
583 I.swapOperands();
584 // Compare instructions are not associative so there's nothing else we can do.
585 return true;
586}
587
Chris Lattner8d969642003-03-10 23:06:50 +0000588// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
589// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000590//
Dan Gohman186a6362009-08-12 16:04:34 +0000591static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000592 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000593 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000594
Chris Lattner0ce85802004-12-14 20:08:06 +0000595 // Constants can be considered to be negated values if they can be folded.
596 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000597 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000598
599 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
600 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000601 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000602
Chris Lattner8d969642003-03-10 23:06:50 +0000603 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000604}
605
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000606// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
607// instruction if the LHS is a constant negative zero (which is the 'negate'
608// form).
609//
Dan Gohman186a6362009-08-12 16:04:34 +0000610static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000611 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000612 return BinaryOperator::getFNegArgument(V);
613
614 // Constants can be considered to be negated values if they can be folded.
615 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000616 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000617
618 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
619 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000620 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000621
622 return 0;
623}
624
Dan Gohman186a6362009-08-12 16:04:34 +0000625static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000626 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000627 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000628
629 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000630 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000631 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000632 return 0;
633}
634
Chris Lattnerc8802d22003-03-11 00:12:48 +0000635// dyn_castFoldableMul - If this value is a multiply that can be folded into
636// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000637// non-constant operand of the multiply, and set CST to point to the multiplier.
638// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000639//
Dan Gohman186a6362009-08-12 16:04:34 +0000640static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000641 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000642 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000643 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000644 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000645 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000646 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000647 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000648 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000649 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000650 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000651 CST = ConstantInt::get(V->getType()->getContext(),
652 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000653 return I->getOperand(0);
654 }
655 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000656 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000657}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000658
Reid Spencer7177c3a2007-03-25 05:33:51 +0000659/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000660static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000661 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000662 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000663}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000664/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000665static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000666 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000667 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000668}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000669/// MultiplyOverflows - True if the multiply can not be expressed in an int
670/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000671static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000672 uint32_t W = C1->getBitWidth();
673 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
674 if (sign) {
675 LHSExt.sext(W * 2);
676 RHSExt.sext(W * 2);
677 } else {
678 LHSExt.zext(W * 2);
679 RHSExt.zext(W * 2);
680 }
681
682 APInt MulExt = LHSExt * RHSExt;
683
684 if (sign) {
685 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
686 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
687 return MulExt.slt(Min) || MulExt.sgt(Max);
688 } else
689 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
690}
Chris Lattner955f3312004-09-28 21:48:02 +0000691
Reid Spencere7816b52007-03-08 01:52:58 +0000692
Chris Lattner255d8912006-02-11 09:31:47 +0000693/// ShrinkDemandedConstant - Check to see if the specified operand of the
694/// specified instruction is a constant integer. If so, check to see if there
695/// are any bits set in the constant that are not demanded. If so, shrink the
696/// constant and return true.
697static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000698 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000699 assert(I && "No instruction?");
700 assert(OpNo < I->getNumOperands() && "Operand index too large");
701
702 // If the operand is not a constant integer, nothing to do.
703 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
704 if (!OpC) return false;
705
706 // If there are no bits set that aren't demanded, nothing to do.
707 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
708 if ((~Demanded & OpC->getValue()) == 0)
709 return false;
710
711 // This instruction is producing bits that are not demanded. Shrink the RHS.
712 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000713 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000714 return true;
715}
716
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
718// set of known zero and one bits, compute the maximum and minimum values that
719// could have the specified known zero and known one bits, returning them in
720// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000721static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000722 const APInt& KnownOne,
723 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000724 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
725 KnownZero.getBitWidth() == Min.getBitWidth() &&
726 KnownZero.getBitWidth() == Max.getBitWidth() &&
727 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000728 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000729
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000730 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
731 // bit if it is unknown.
732 Min = KnownOne;
733 Max = KnownOne|UnknownBits;
734
Dan Gohman1c8491e2009-04-25 17:12:48 +0000735 if (UnknownBits.isNegative()) { // Sign bit is unknown
736 Min.set(Min.getBitWidth()-1);
737 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000738 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000739}
740
741// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
742// a set of known zero and one bits, compute the maximum and minimum values that
743// could have the specified known zero and known one bits, returning them in
744// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000745static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000746 const APInt &KnownOne,
747 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000748 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
749 KnownZero.getBitWidth() == Min.getBitWidth() &&
750 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000751 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000752 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000753
754 // The minimum value is when the unknown bits are all zeros.
755 Min = KnownOne;
756 // The maximum value is when the unknown bits are all ones.
757 Max = KnownOne|UnknownBits;
758}
Chris Lattner255d8912006-02-11 09:31:47 +0000759
Chris Lattner886ab6c2009-01-31 08:15:18 +0000760/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
761/// SimplifyDemandedBits knows about. See if the instruction has any
762/// properties that allow us to simplify its operands.
763bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000764 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000765 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
766 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
767
768 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
769 KnownZero, KnownOne, 0);
770 if (V == 0) return false;
771 if (V == &Inst) return true;
772 ReplaceInstUsesWith(Inst, V);
773 return true;
774}
775
776/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
777/// specified instruction operand if possible, updating it in place. It returns
778/// true if it made any change and false otherwise.
779bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
780 APInt &KnownZero, APInt &KnownOne,
781 unsigned Depth) {
782 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
783 KnownZero, KnownOne, Depth);
784 if (NewVal == 0) return false;
785 U.set(NewVal);
786 return true;
787}
788
789
790/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
791/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000792/// that only the bits set in DemandedMask of the result of V are ever used
793/// downstream. Consequently, depending on the mask and V, it may be possible
794/// to replace V with a constant or one of its operands. In such cases, this
795/// function does the replacement and returns true. In all other cases, it
796/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000797/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000798/// to be zero in the expression. These are provided to potentially allow the
799/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
800/// the expression. KnownOne and KnownZero always follow the invariant that
801/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
802/// the bits in KnownOne and KnownZero may only be accurate for those bits set
803/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
804/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000805///
806/// This returns null if it did not change anything and it permits no
807/// simplification. This returns V itself if it did some simplification of V's
808/// operands based on the information about what bits are demanded. This returns
809/// some other non-null value if it found out that V is equal to another value
810/// in the context where the specified bits are demanded, but not for all users.
811Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
812 APInt &KnownZero, APInt &KnownOne,
813 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000814 assert(V != 0 && "Null pointer of Value???");
815 assert(Depth <= 6 && "Limit Search Depth");
816 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000817 const Type *VTy = V->getType();
818 assert((TD || !isa<PointerType>(VTy)) &&
819 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000820 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
821 (!VTy->isIntOrIntVector() ||
822 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000823 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000824 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000825 "Value *V, DemandedMask, KnownZero and KnownOne "
826 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
828 // We know all of the bits for a constant!
829 KnownOne = CI->getValue() & DemandedMask;
830 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000831 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000832 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000833 if (isa<ConstantPointerNull>(V)) {
834 // We know all of the bits for a constant!
835 KnownOne.clear();
836 KnownZero = DemandedMask;
837 return 0;
838 }
839
Chris Lattner08d2cc72009-01-31 07:26:06 +0000840 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000841 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000842 if (DemandedMask == 0) { // Not demanding any bits from V.
843 if (isa<UndefValue>(V))
844 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000845 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000846 }
847
Chris Lattner4598c942009-01-31 08:24:16 +0000848 if (Depth == 6) // Limit search depth.
849 return 0;
850
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000851 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
852 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
853
Dan Gohman1c8491e2009-04-25 17:12:48 +0000854 Instruction *I = dyn_cast<Instruction>(V);
855 if (!I) {
856 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
857 return 0; // Only analyze instructions.
858 }
859
Chris Lattner4598c942009-01-31 08:24:16 +0000860 // If there are multiple uses of this value and we aren't at the root, then
861 // we can't do any simplifications of the operands, because DemandedMask
862 // only reflects the bits demanded by *one* of the users.
863 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000864 // Despite the fact that we can't simplify this instruction in all User's
865 // context, we can at least compute the knownzero/knownone bits, and we can
866 // do simplifications that apply to *just* the one user if we know that
867 // this instruction has a simpler value in that context.
868 if (I->getOpcode() == Instruction::And) {
869 // If either the LHS or the RHS are Zero, the result is zero.
870 ComputeMaskedBits(I->getOperand(1), DemandedMask,
871 RHSKnownZero, RHSKnownOne, Depth+1);
872 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
873 LHSKnownZero, LHSKnownOne, Depth+1);
874
875 // If all of the demanded bits are known 1 on one side, return the other.
876 // These bits cannot contribute to the result of the 'and' in this
877 // context.
878 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
879 (DemandedMask & ~LHSKnownZero))
880 return I->getOperand(0);
881 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
882 (DemandedMask & ~RHSKnownZero))
883 return I->getOperand(1);
884
885 // If all of the demanded bits in the inputs are known zeros, return zero.
886 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000887 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000888
889 } else if (I->getOpcode() == Instruction::Or) {
890 // We can simplify (X|Y) -> X or Y in the user's context if we know that
891 // only bits from X or Y are demanded.
892
893 // If either the LHS or the RHS are One, the result is One.
894 ComputeMaskedBits(I->getOperand(1), DemandedMask,
895 RHSKnownZero, RHSKnownOne, Depth+1);
896 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
897 LHSKnownZero, LHSKnownOne, Depth+1);
898
899 // If all of the demanded bits are known zero on one side, return the
900 // other. These bits cannot contribute to the result of the 'or' in this
901 // context.
902 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
903 (DemandedMask & ~LHSKnownOne))
904 return I->getOperand(0);
905 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
906 (DemandedMask & ~RHSKnownOne))
907 return I->getOperand(1);
908
909 // If all of the potentially set bits on one side are known to be set on
910 // the other side, just use the 'other' side.
911 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
912 (DemandedMask & (~RHSKnownZero)))
913 return I->getOperand(0);
914 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
915 (DemandedMask & (~LHSKnownZero)))
916 return I->getOperand(1);
917 }
918
Chris Lattner4598c942009-01-31 08:24:16 +0000919 // Compute the KnownZero/KnownOne bits to simplify things downstream.
920 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
921 return 0;
922 }
923
924 // If this is the root being simplified, allow it to have multiple uses,
925 // just set the DemandedMask to all bits so that we can try to simplify the
926 // operands. This allows visitTruncInst (for example) to simplify the
927 // operand of a trunc without duplicating all the logic below.
928 if (Depth == 0 && !V->hasOneUse())
929 DemandedMask = APInt::getAllOnesValue(BitWidth);
930
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000932 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000934 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000935 case Instruction::And:
936 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000937 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
938 RHSKnownZero, RHSKnownOne, Depth+1) ||
939 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000940 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 return I;
942 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
943 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000944
945 // If all of the demanded bits are known 1 on one side, return the other.
946 // These bits cannot contribute to the result of the 'and'.
947 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
948 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000949 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000950 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
951 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953
954 // If all of the demanded bits in the inputs are known zeros, return zero.
955 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000956 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000959 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000961
962 // Output known-1 bits are only known if set in both the LHS & RHS.
963 RHSKnownOne &= LHSKnownOne;
964 // Output known-0 are known to be clear if zero in either the LHS | RHS.
965 RHSKnownZero |= LHSKnownZero;
966 break;
967 case Instruction::Or:
968 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
970 RHSKnownZero, RHSKnownOne, Depth+1) ||
971 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I;
974 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
975 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000976
977 // If all of the demanded bits are known zero on one side, return the other.
978 // These bits cannot contribute to the result of the 'or'.
979 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
980 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000982 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
983 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000985
986 // If all of the potentially set bits on one side are known to be set on
987 // the other side, just use the 'other' side.
988 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
989 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
992 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000996 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000998
999 // Output known-0 bits are only known if clear in both the LHS & RHS.
1000 RHSKnownZero &= LHSKnownZero;
1001 // Output known-1 are known to be set if set in either the LHS | RHS.
1002 RHSKnownOne |= LHSKnownOne;
1003 break;
1004 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1006 RHSKnownZero, RHSKnownOne, Depth+1) ||
1007 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001008 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001009 return I;
1010 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1011 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001012
1013 // If all of the demanded bits are known zero on one side, return the other.
1014 // These bits cannot contribute to the result of the 'xor'.
1015 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019
1020 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1021 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1022 (RHSKnownOne & LHSKnownOne);
1023 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1024 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1025 (RHSKnownOne & LHSKnownZero);
1026
1027 // If all of the demanded bits are known to be zero on one side or the
1028 // other, turn this into an *inclusive* or.
1029 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1030 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1031 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001032 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001033 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001035 }
1036
1037 // If all of the demanded bits on one side are known, and all of the set
1038 // bits on that side are also known to be set on the other side, turn this
1039 // into an AND, as we know the bits will be cleared.
1040 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1041 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1042 // all known
1043 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001044 Constant *AndC = Constant::getIntegerValue(VTy,
1045 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001047 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001049 }
1050 }
1051
1052 // If the RHS is a constant, see if we can simplify it.
1053 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001054 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001056
1057 RHSKnownZero = KnownZeroOut;
1058 RHSKnownOne = KnownOneOut;
1059 break;
1060 }
1061 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1063 RHSKnownZero, RHSKnownOne, Depth+1) ||
1064 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001065 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001066 return I;
1067 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1068 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001069
1070 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001071 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1072 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
1075 // Only known if known in both the LHS and RHS.
1076 RHSKnownOne &= LHSKnownOne;
1077 RHSKnownZero &= LHSKnownZero;
1078 break;
1079 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001080 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001081 DemandedMask.zext(truncBf);
1082 RHSKnownZero.zext(truncBf);
1083 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001085 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001086 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 DemandedMask.trunc(BitWidth);
1088 RHSKnownZero.trunc(BitWidth);
1089 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001091 break;
1092 }
1093 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001094 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001095 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001096
1097 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1098 if (const VectorType *SrcVTy =
1099 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1100 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1101 // Don't touch a bitcast between vectors of different element counts.
1102 return false;
1103 } else
1104 // Don't touch a scalar-to-vector bitcast.
1105 return false;
1106 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1107 // Don't touch a vector-to-scalar bitcast.
1108 return false;
1109
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001111 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 return I;
1113 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001114 break;
1115 case Instruction::ZExt: {
1116 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001117 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001118
Zhou Shengd48653a2007-03-29 04:45:55 +00001119 DemandedMask.trunc(SrcBitWidth);
1120 RHSKnownZero.trunc(SrcBitWidth);
1121 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001123 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 DemandedMask.zext(BitWidth);
1126 RHSKnownZero.zext(BitWidth);
1127 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 break;
1132 }
1133 case Instruction::SExt: {
1134 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001135 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001136
Reid Spencer8cb68342007-03-12 17:25:59 +00001137 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001139
Zhou Sheng01542f32007-03-29 02:26:30 +00001140 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001141 // If any of the sign extended bits are demanded, we know that the sign
1142 // bit is demanded.
1143 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001144 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001145
Zhou Shengd48653a2007-03-29 04:45:55 +00001146 InputDemandedBits.trunc(SrcBitWidth);
1147 RHSKnownZero.trunc(SrcBitWidth);
1148 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001150 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001151 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001152 InputDemandedBits.zext(BitWidth);
1153 RHSKnownZero.zext(BitWidth);
1154 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001155 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001156
1157 // If the sign bit of the input is known set or clear, then we know the
1158 // top bits of the result.
1159
1160 // If the input sign bit is known zero, or if the NewBits are not demanded
1161 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1165 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001166 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001168 }
1169 break;
1170 }
1171 case Instruction::Add: {
1172 // Figure out what the input bits are. If the top bits of the and result
1173 // are not demanded, then the add doesn't demand them from its input
1174 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001175 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // If there is a constant on the RHS, there are a variety of xformations
1178 // we can do.
1179 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1180 // If null, this should be simplified elsewhere. Some of the xforms here
1181 // won't work if the RHS is zero.
1182 if (RHS->isZero())
1183 break;
1184
1185 // If the top bit of the output is demanded, demand everything from the
1186 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001187 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001188
1189 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001191 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001193
1194 // If the RHS of the add has bits set that can't affect the input, reduce
1195 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001196 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001197 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001198
1199 // Avoid excess work.
1200 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1201 break;
1202
1203 // Turn it into OR if input bits are zero.
1204 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1205 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001206 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001208 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 }
1210
1211 // We can say something about the output known-zero and known-one bits,
1212 // depending on potential carries from the input constant and the
1213 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1214 // bits set and the RHS constant is 0x01001, then we know we have a known
1215 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1216
1217 // To compute this, we first compute the potential carry bits. These are
1218 // the bits which may be modified. I'm not aware of a better way to do
1219 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001220 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001221 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001222
1223 // Now that we know which bits have carries, compute the known-1/0 sets.
1224
1225 // Bits are known one if they are known zero in one operand and one in the
1226 // other, and there is no input carry.
1227 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1228 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1229
1230 // Bits are known zero if they are known zero in both operands and there
1231 // is no input carry.
1232 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1233 } else {
1234 // If the high-bits of this ADD are not demanded, then it does not demand
1235 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001236 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 // Right fill the mask of bits for this ADD to demand the most
1238 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001239 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1241 LHSKnownZero, LHSKnownOne, Depth+1) ||
1242 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001244 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 }
1246 }
1247 break;
1248 }
1249 case Instruction::Sub:
1250 // If the high-bits of this SUB are not demanded, then it does not demand
1251 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001252 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 // Right fill the mask of bits for this SUB to demand the most
1254 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001255 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001256 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001257 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1258 LHSKnownZero, LHSKnownOne, Depth+1) ||
1259 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001263 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1264 // the known zeros and ones.
1265 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 break;
1267 case Instruction::Shl:
1268 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001269 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001270 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 return I;
1274 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 RHSKnownZero <<= ShiftAmt;
1276 RHSKnownOne <<= ShiftAmt;
1277 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001278 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001279 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 }
1281 break;
1282 case Instruction::LShr:
1283 // For a logical shift right
1284 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001285 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001286
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001288 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 return I;
1292 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1294 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001295 if (ShiftAmt) {
1296 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001297 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001298 RHSKnownZero |= HighBits; // high bits known zero.
1299 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 }
1301 break;
1302 case Instruction::AShr:
1303 // If this is an arithmetic shift right and only the low-bit is set, we can
1304 // always convert this into a logical shr, even if the shift amount is
1305 // variable. The low bit of the shift cannot be an input sign bit unless
1306 // the shift amount is >= the size of the datatype, which is undefined.
1307 if (DemandedMask == 1) {
1308 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001313
1314 // If the sign bit is the only bit demanded by this ashr, then there is no
1315 // need to do it, the shift doesn't change the high bit.
1316 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001317 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001318
1319 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001320 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001321
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001323 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001324 // If any of the "high bits" are demanded, we should set the sign bit as
1325 // demanded.
1326 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1327 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001328 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001330 return I;
1331 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001333 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001334 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1335 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1336
1337 // Handle the sign bits.
1338 APInt SignBit(APInt::getSignBit(BitWidth));
1339 // Adjust to where it is now in the mask.
1340 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1341
1342 // If the input sign bit is known to be zero, or if none of the top bits
1343 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001344 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001345 (HighBits & ~DemandedMask) == HighBits) {
1346 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1351 RHSKnownOne |= HighBits;
1352 }
1353 }
1354 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355 case Instruction::SRem:
1356 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001357 APInt RA = Rem->getValue().abs();
1358 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001359 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001360 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001361
Nick Lewycky8e394322008-11-02 02:41:50 +00001362 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001363 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001366 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001367
1368 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1369 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370
1371 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372
Chris Lattner886ab6c2009-01-31 08:15:18 +00001373 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001374 }
1375 }
1376 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001377 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001378 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1379 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001380 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1381 KnownZero2, KnownOne2, Depth+1) ||
1382 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001383 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001384 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001385
Chris Lattner455e9ab2009-01-21 18:09:24 +00001386 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001387 Leaders = std::max(Leaders,
1388 KnownZero2.countLeadingOnes());
1389 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001390 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001391 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001392 case Instruction::Call:
1393 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1394 switch (II->getIntrinsicID()) {
1395 default: break;
1396 case Intrinsic::bswap: {
1397 // If the only bits demanded come from one byte of the bswap result,
1398 // just shift the input byte into position to eliminate the bswap.
1399 unsigned NLZ = DemandedMask.countLeadingZeros();
1400 unsigned NTZ = DemandedMask.countTrailingZeros();
1401
1402 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1403 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1404 // have 14 leading zeros, round to 8.
1405 NLZ &= ~7;
1406 NTZ &= ~7;
1407 // If we need exactly one byte, we can do this transformation.
1408 if (BitWidth-NLZ-NTZ == 8) {
1409 unsigned ResultBit = NTZ;
1410 unsigned InputBit = BitWidth-NTZ-8;
1411
1412 // Replace this with either a left or right shift to get the byte into
1413 // the right place.
1414 Instruction *NewVal;
1415 if (InputBit > ResultBit)
1416 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001417 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001418 else
1419 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001420 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001421 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001422 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001423 }
1424
1425 // TODO: Could compute known zero/one bits based on the input.
1426 break;
1427 }
1428 }
1429 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001430 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001431 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001432 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001433
1434 // If the client is only demanding bits that we know, return the known
1435 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001436 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1437 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001438 return false;
1439}
1440
Chris Lattner867b99f2006-10-05 06:55:50 +00001441
Mon P Wangaeb06d22008-11-10 04:46:22 +00001442/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001443/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001444/// actually used by the caller. This method analyzes which elements of the
1445/// operand are undef and returns that information in UndefElts.
1446///
1447/// If the information about demanded elements can be used to simplify the
1448/// operation, the operation is simplified, then the resultant value is
1449/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001450Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1451 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001454 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001455 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001456
1457 if (isa<UndefValue>(V)) {
1458 // If the entire vector is undefined, just return this info.
1459 UndefElts = EltMask;
1460 return 0;
1461 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1462 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001463 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001465
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001467 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1468 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001469 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001470
1471 std::vector<Constant*> Elts;
1472 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001473 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001474 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001475 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1477 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001478 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001479 } else { // Otherwise, defined.
1480 Elts.push_back(CP->getOperand(i));
1481 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001482
Chris Lattner867b99f2006-10-05 06:55:50 +00001483 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001484 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 return NewCP != CP ? NewCP : 0;
1486 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001487 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001489
1490 // Check if this is identity. If so, return 0 since we are not simplifying
1491 // anything.
1492 if (DemandedElts == ((1ULL << VWidth) -1))
1493 return 0;
1494
Reid Spencer9d6565a2007-02-15 02:26:10 +00001495 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001496 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001497 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001498 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001499 for (unsigned i = 0; i != VWidth; ++i) {
1500 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1501 Elts.push_back(Elt);
1502 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001504 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 }
1506
Dan Gohman488fbfc2008-09-09 18:11:14 +00001507 // Limit search depth.
1508 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001509 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001510
1511 // If multiple users are using the root value, procede with
1512 // simplification conservatively assuming that all elements
1513 // are needed.
1514 if (!V->hasOneUse()) {
1515 // Quit if we find multiple users of a non-root value though.
1516 // They'll be handled when it's their turn to be visited by
1517 // the main instcombine process.
1518 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001520 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001521
1522 // Conservatively assume that all elements are needed.
1523 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 }
1525
1526 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001527 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001528
1529 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001530 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 Value *TmpV;
1532 switch (I->getOpcode()) {
1533 default: break;
1534
1535 case Instruction::InsertElement: {
1536 // If this is a variable index, we don't know which element it overwrites.
1537 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001538 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001539 if (Idx == 0) {
1540 // Note that we can't propagate undef elt info, because we don't know
1541 // which elt is getting updated.
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1543 UndefElts2, Depth+1);
1544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545 break;
1546 }
1547
1548 // If this is inserting an element that isn't demanded, remove this
1549 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001550 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001551 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001552 return AddSoonDeadInstToWorklist(*I, 0);
1553
1554 // Otherwise, the element inserted overwrites whatever was there, so the
1555 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001556 APInt DemandedElts2 = DemandedElts;
1557 DemandedElts2.clear(IdxNo);
1558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001559 UndefElts, Depth+1);
1560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
1562 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001563 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001564 break;
1565 }
1566 case Instruction::ShuffleVector: {
1567 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001568 uint64_t LHSVWidth =
1569 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001570 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001572 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 unsigned MaskVal = Shuffle->getMaskValue(i);
1574 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001575 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001577 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001578 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001579 else
Evan Cheng388df622009-02-03 10:05:09 +00001580 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 }
1582 }
1583 }
1584
Nate Begeman7b254672009-02-11 22:36:25 +00001585 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001587 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1589
Nate Begeman7b254672009-02-11 22:36:25 +00001590 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1592 UndefElts3, Depth+1);
1593 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1594
1595 bool NewUndefElts = false;
1596 for (unsigned i = 0; i < VWidth; i++) {
1597 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001598 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001599 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001600 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001601 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001602 NewUndefElts = true;
1603 UndefElts.set(i);
1604 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001605 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001606 if (UndefElts3[MaskVal - LHSVWidth]) {
1607 NewUndefElts = true;
1608 UndefElts.set(i);
1609 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 }
1611 }
1612
1613 if (NewUndefElts) {
1614 // Add additional discovered undefs.
1615 std::vector<Constant*> Elts;
1616 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001617 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001618 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001619 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001620 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001621 Shuffle->getMaskValue(i)));
1622 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001623 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001624 MadeChange = true;
1625 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001626 break;
1627 }
Chris Lattner69878332007-04-14 22:29:23 +00001628 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001629 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001630 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1631 if (!VTy) break;
1632 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001633 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001634 unsigned Ratio;
1635
1636 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001637 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001638 // elements as are demanded of us.
1639 Ratio = 1;
1640 InputDemandedElts = DemandedElts;
1641 } else if (VWidth > InVWidth) {
1642 // Untested so far.
1643 break;
1644
1645 // If there are more elements in the result than there are in the source,
1646 // then an input element is live if any of the corresponding output
1647 // elements are live.
1648 Ratio = VWidth/InVWidth;
1649 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001650 if (DemandedElts[OutIdx])
1651 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001652 }
1653 } else {
1654 // Untested so far.
1655 break;
1656
1657 // If there are more elements in the source than there are in the result,
1658 // then an input element is live if the corresponding output element is
1659 // live.
1660 Ratio = InVWidth/VWidth;
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001662 if (DemandedElts[InIdx/Ratio])
1663 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001664 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001665
Chris Lattner69878332007-04-14 22:29:23 +00001666 // div/rem demand all inputs, because they don't want divide by zero.
1667 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1668 UndefElts2, Depth+1);
1669 if (TmpV) {
1670 I->setOperand(0, TmpV);
1671 MadeChange = true;
1672 }
1673
1674 UndefElts = UndefElts2;
1675 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001676 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001677 // If there are more elements in the result than there are in the source,
1678 // then an output element is undef if the corresponding input element is
1679 // undef.
1680 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001681 if (UndefElts2[OutIdx/Ratio])
1682 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001683 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001684 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001685 // If there are more elements in the source than there are in the result,
1686 // then a result element is undef if all of the corresponding input
1687 // elements are undef.
1688 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1689 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001690 if (!UndefElts2[InIdx]) // Not undef?
1691 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001692 }
1693 break;
1694 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001695 case Instruction::And:
1696 case Instruction::Or:
1697 case Instruction::Xor:
1698 case Instruction::Add:
1699 case Instruction::Sub:
1700 case Instruction::Mul:
1701 // div/rem demand all inputs, because they don't want divide by zero.
1702 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1708
1709 // Output elements are undefined if both are undefined. Consider things
1710 // like undef&0. The result is known zero, not undef.
1711 UndefElts &= UndefElts2;
1712 break;
1713
1714 case Instruction::Call: {
1715 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1716 if (!II) break;
1717 switch (II->getIntrinsicID()) {
1718 default: break;
1719
1720 // Binary vector operations that work column-wise. A dest element is a
1721 // function of the corresponding input elements from the two inputs.
1722 case Intrinsic::x86_sse_sub_ss:
1723 case Intrinsic::x86_sse_mul_ss:
1724 case Intrinsic::x86_sse_min_ss:
1725 case Intrinsic::x86_sse_max_ss:
1726 case Intrinsic::x86_sse2_sub_sd:
1727 case Intrinsic::x86_sse2_mul_sd:
1728 case Intrinsic::x86_sse2_min_sd:
1729 case Intrinsic::x86_sse2_max_sd:
1730 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1731 UndefElts, Depth+1);
1732 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1733 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1734 UndefElts2, Depth+1);
1735 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1736
1737 // If only the low elt is demanded and this is a scalarizable intrinsic,
1738 // scalarize it now.
1739 if (DemandedElts == 1) {
1740 switch (II->getIntrinsicID()) {
1741 default: break;
1742 case Intrinsic::x86_sse_sub_ss:
1743 case Intrinsic::x86_sse_mul_ss:
1744 case Intrinsic::x86_sse2_sub_sd:
1745 case Intrinsic::x86_sse2_mul_sd:
1746 // TODO: Lower MIN/MAX/ABS/etc
1747 Value *LHS = II->getOperand(1);
1748 Value *RHS = II->getOperand(2);
1749 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001750 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001751 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001752 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001753 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001754
1755 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001756 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001757 case Intrinsic::x86_sse_sub_ss:
1758 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001759 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001760 II->getName()), *II);
1761 break;
1762 case Intrinsic::x86_sse_mul_ss:
1763 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001764 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001765 II->getName()), *II);
1766 break;
1767 }
1768
1769 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001770 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001771 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001772 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001773 InsertNewInstBefore(New, *II);
1774 AddSoonDeadInstToWorklist(*II, 0);
1775 return New;
1776 }
1777 }
1778
1779 // Output elements are undefined if both are undefined. Consider things
1780 // like undef&0. The result is known zero, not undef.
1781 UndefElts &= UndefElts2;
1782 break;
1783 }
1784 break;
1785 }
1786 }
1787 return MadeChange ? I : 0;
1788}
1789
Dan Gohman45b4e482008-05-19 22:14:15 +00001790
Chris Lattner564a7272003-08-13 19:01:45 +00001791/// AssociativeOpt - Perform an optimization on an associative operator. This
1792/// function is designed to check a chain of associative operators for a
1793/// potential to apply a certain optimization. Since the optimization may be
1794/// applicable if the expression was reassociated, this checks the chain, then
1795/// reassociates the expression as necessary to expose the optimization
1796/// opportunity. This makes use of a special Functor, which must define
1797/// 'shouldApply' and 'apply' methods.
1798///
1799template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001800static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001801 unsigned Opcode = Root.getOpcode();
1802 Value *LHS = Root.getOperand(0);
1803
1804 // Quick check, see if the immediate LHS matches...
1805 if (F.shouldApply(LHS))
1806 return F.apply(Root);
1807
1808 // Otherwise, if the LHS is not of the same opcode as the root, return.
1809 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001810 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001811 // Should we apply this transform to the RHS?
1812 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1813
1814 // If not to the RHS, check to see if we should apply to the LHS...
1815 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1816 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1817 ShouldApply = true;
1818 }
1819
1820 // If the functor wants to apply the optimization to the RHS of LHSI,
1821 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1822 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001823 // Now all of the instructions are in the current basic block, go ahead
1824 // and perform the reassociation.
1825 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1826
1827 // First move the selected RHS to the LHS of the root...
1828 Root.setOperand(0, LHSI->getOperand(1));
1829
1830 // Make what used to be the LHS of the root be the user of the root...
1831 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001832 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001833 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001834 return 0;
1835 }
Chris Lattner65725312004-04-16 18:08:07 +00001836 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001837 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001838 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001839 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001840 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001841
1842 // Now propagate the ExtraOperand down the chain of instructions until we
1843 // get to LHSI.
1844 while (TmpLHSI != LHSI) {
1845 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001846 // Move the instruction to immediately before the chain we are
1847 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001848 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001849 ARI = NextLHSI;
1850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 Value *NextOp = NextLHSI->getOperand(1);
1852 NextLHSI->setOperand(1, ExtraOperand);
1853 TmpLHSI = NextLHSI;
1854 ExtraOperand = NextOp;
1855 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001856
Chris Lattner564a7272003-08-13 19:01:45 +00001857 // Now that the instructions are reassociated, have the functor perform
1858 // the transformation...
1859 return F.apply(Root);
1860 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001861
Chris Lattner564a7272003-08-13 19:01:45 +00001862 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1863 }
1864 return 0;
1865}
1866
Dan Gohman844731a2008-05-13 00:00:25 +00001867namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001868
Nick Lewycky02d639f2008-05-23 04:34:58 +00001869// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001870struct AddRHS {
1871 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001872 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001873 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1874 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001875 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001876 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001877 }
1878};
1879
1880// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1881// iff C1&C2 == 0
1882struct AddMaskingAnd {
1883 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001884 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001885 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001886 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001887 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001888 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001889 }
1890 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001891 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001892 }
1893};
1894
Dan Gohman844731a2008-05-13 00:00:25 +00001895}
1896
Chris Lattner6e7ba452005-01-01 16:22:27 +00001897static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001899 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001900 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001901 }
1902
Chris Lattner2eefe512004-04-09 19:05:30 +00001903 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1905 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001906
Chris Lattner2eefe512004-04-09 19:05:30 +00001907 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1908 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001909 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1910 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001911 }
1912
1913 Value *Op0 = SO, *Op1 = ConstOperand;
1914 if (!ConstIsRHS)
1915 std::swap(Op0, Op1);
1916 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001918 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001919 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001920 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00001921 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001922 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001923 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001924 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 return IC->InsertNewInstBefore(New, I);
1926}
1927
1928// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1929// constant as the other operand, try to fold the binary operator into the
1930// select arguments. This also works for Cast instructions, which obviously do
1931// not have a second operand.
1932static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1933 InstCombiner *IC) {
1934 // Don't modify shared select instructions
1935 if (!SI->hasOneUse()) return 0;
1936 Value *TV = SI->getOperand(1);
1937 Value *FV = SI->getOperand(2);
1938
1939 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001940 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001941 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001942
Chris Lattner6e7ba452005-01-01 16:22:27 +00001943 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1944 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1945
Gabor Greif051a9502008-04-06 20:25:17 +00001946 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1947 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001948 }
1949 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001950}
1951
Chris Lattner4e998b22004-09-29 05:07:12 +00001952
1953/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1954/// node as operand #0, see if we can fold the instruction into the PHI (which
1955/// is only possible if all operands to the PHI are constants).
1956Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1957 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001958 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001960
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 // Check to see if all of the operands of the PHI are constants. If there is
1962 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001963 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001964 BasicBlock *NonConstBB = 0;
1965 for (unsigned i = 0; i != NumPHIValues; ++i)
1966 if (!isa<Constant>(PN->getIncomingValue(i))) {
1967 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001968 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001969 NonConstBB = PN->getIncomingBlock(i);
1970
1971 // If the incoming non-constant value is in I's block, we have an infinite
1972 // loop.
1973 if (NonConstBB == I.getParent())
1974 return 0;
1975 }
1976
1977 // If there is exactly one non-constant value, we can insert a copy of the
1978 // operation in that block. However, if this is a critical edge, we would be
1979 // inserting the computation one some other paths (e.g. inside a loop). Only
1980 // do this if the pred block is unconditionally branching into the phi block.
1981 if (NonConstBB) {
1982 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1983 if (!BI || !BI->isUnconditional()) return 0;
1984 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001985
1986 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001987 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001988 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001989 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001990 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001991
1992 // Next, add all of the operands to the PHI.
1993 if (I.getNumOperands() == 2) {
1994 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001995 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001996 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001998 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001999 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002000 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002001 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 } else {
2003 assert(PN->getIncomingBlock(i) == NonConstBB);
2004 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 PN->getIncomingValue(i), C, "phitmp",
2007 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002008 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002009 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002010 CI->getPredicate(),
2011 PN->getIncomingValue(i), C, "phitmp",
2012 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002014 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015
Chris Lattner7a1e9242009-08-30 06:13:40 +00002016 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 }
2018 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002019 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002020 } else {
2021 CastInst *CI = cast<CastInst>(&I);
2022 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002023 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 Value *InV;
2025 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002026 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002027 } else {
2028 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002029 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002030 I.getType(), "phitmp",
2031 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002032 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002033 }
2034 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002035 }
2036 }
2037 return ReplaceInstUsesWith(I, NewPN);
2038}
2039
Chris Lattner2454a2e2008-01-29 06:52:45 +00002040
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002041/// WillNotOverflowSignedAdd - Return true if we can prove that:
2042/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2043/// This basically requires proving that the add in the original type would not
2044/// overflow to change the sign bit or have a carry out.
2045bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2046 // There are different heuristics we can use for this. Here are some simple
2047 // ones.
2048
2049 // Add has the property that adding any two 2's complement numbers can only
2050 // have one carry bit which can change a sign. As such, if LHS and RHS each
2051 // have at least two sign bits, we know that the addition of the two values will
2052 // sign extend fine.
2053 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2054 return true;
2055
2056
2057 // If one of the operands only has one non-zero bit, and if the other operand
2058 // has a known-zero bit in a more significant place than it (not including the
2059 // sign bit) the ripple may go up to and fill the zero, but won't change the
2060 // sign. For example, (X & ~4) + 1.
2061
2062 // TODO: Implement.
2063
2064 return false;
2065}
2066
Chris Lattner2454a2e2008-01-29 06:52:45 +00002067
Chris Lattner7e708292002-06-25 16:13:24 +00002068Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002069 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002070 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002071
Chris Lattner66331a42004-04-10 22:01:55 +00002072 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002073 // X + undef -> undef
2074 if (isa<UndefValue>(RHS))
2075 return ReplaceInstUsesWith(I, RHS);
2076
Chris Lattner66331a42004-04-10 22:01:55 +00002077 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002078 if (RHSC->isNullValue())
2079 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002080
Chris Lattner66331a42004-04-10 22:01:55 +00002081 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002082 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002083 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002084 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002085 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002086 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002087
2088 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2089 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002090 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002091 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002092
Eli Friedman709b33d2009-07-13 22:27:52 +00002093 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002094 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002095 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002096 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002097 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002098
2099 if (isa<PHINode>(LHS))
2100 if (Instruction *NV = FoldOpIntoPhi(I))
2101 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002102
Chris Lattner4f637d42006-01-06 17:59:59 +00002103 ConstantInt *XorRHS = 0;
2104 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002105 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002106 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002107 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002108 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002109
Zhou Sheng4351c642007-04-02 08:20:41 +00002110 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002111 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2112 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002113 do {
2114 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002115 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2116 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002117 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2118 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002119 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002120 if (!MaskedValueIsZero(XorLHS,
2121 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002122 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002123 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002124 }
2125 }
2126 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002127 C0080Val = APIntOps::lshr(C0080Val, Size);
2128 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2129 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002130
Reid Spencer35c38852007-03-28 01:36:16 +00002131 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002132 // with funny bit widths then this switch statement should be removed. It
2133 // is just here to get the size of the "middle" type back up to something
2134 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002135 const Type *MiddleType = 0;
2136 switch (Size) {
2137 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002138 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2139 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2140 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002141 }
2142 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002143 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002144 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002145 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002146 }
2147 }
Chris Lattner66331a42004-04-10 22:01:55 +00002148 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002149
Owen Anderson1d0be152009-08-13 21:58:54 +00002150 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002151 return BinaryOperator::CreateXor(LHS, RHS);
2152
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002153 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002154 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002155 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002156 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002157
2158 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2159 if (RHSI->getOpcode() == Instruction::Sub)
2160 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2161 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2162 }
2163 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2164 if (LHSI->getOpcode() == Instruction::Sub)
2165 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2166 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2167 }
Robert Bocchino71698282004-07-27 21:02:21 +00002168 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002169
Chris Lattner5c4afb92002-05-08 22:46:53 +00002170 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002171 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002172 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002173 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002174 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002175 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002176 InsertNewInstBefore(NewAdd, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00002177 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002178 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002179 }
2180
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002181 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002182 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002183
2184 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002185 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002186 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002187 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002188
Misha Brukmanfd939082005-04-21 23:48:37 +00002189
Chris Lattner50af16a2004-11-13 19:50:12 +00002190 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002191 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002192 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002193 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002194
2195 // X*C1 + X*C2 --> X * (C1+C2)
2196 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002197 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002198 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002199 }
2200
2201 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002202 if (dyn_castFoldableMul(RHS, C2) == LHS)
2203 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002204
Chris Lattnere617c9e2007-01-05 02:17:46 +00002205 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002206 if (dyn_castNotVal(LHS) == RHS ||
2207 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002208 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002209
Chris Lattnerad3448c2003-02-18 19:57:07 +00002210
Chris Lattner564a7272003-08-13 19:01:45 +00002211 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002212 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2213 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002214 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002215
2216 // A+B --> A|B iff A and B have no bits set in common.
2217 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2218 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2219 APInt LHSKnownOne(IT->getBitWidth(), 0);
2220 APInt LHSKnownZero(IT->getBitWidth(), 0);
2221 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2222 if (LHSKnownZero != 0) {
2223 APInt RHSKnownOne(IT->getBitWidth(), 0);
2224 APInt RHSKnownZero(IT->getBitWidth(), 0);
2225 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2226
2227 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002228 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002229 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002230 }
2231 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002232
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002233 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002234 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002235 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002236 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2237 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002238 if (W != Y) {
2239 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002240 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002241 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002242 std::swap(W, X);
2243 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002244 std::swap(Y, Z);
2245 std::swap(W, X);
2246 }
2247 }
2248
2249 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002250 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002251 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002252 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002253 }
2254 }
2255 }
2256
Chris Lattner6b032052003-10-02 15:11:26 +00002257 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002258 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002259 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002260 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002261
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002263 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002264 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002265 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266 if (Anded == CRHS) {
2267 // See if all bits from the first bit set in the Add RHS up are included
2268 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002269 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270
2271 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002272 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273
2274 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002275 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002276
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2278 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002279 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002281 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002282 }
2283 }
2284 }
2285
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002286 // Try to fold constant add into select arguments.
2287 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002288 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002289 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002290 }
2291
Chris Lattner42790482007-12-20 01:56:58 +00002292 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002293 {
2294 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002295 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002296 if (!SI) {
2297 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002298 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002299 }
Chris Lattner42790482007-12-20 01:56:58 +00002300 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002301 Value *TV = SI->getTrueValue();
2302 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002303 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002304
2305 // Can we fold the add into the argument of the select?
2306 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002307 if (match(FV, m_Zero()) &&
2308 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002309 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002310 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002311 if (match(TV, m_Zero()) &&
2312 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002313 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002314 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002315 }
2316 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002317
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002318 // Check for (add (sext x), y), see if we can merge this into an
2319 // integer add followed by a sext.
2320 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2321 // (add (sext x), cst) --> (sext (add x, cst'))
2322 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2323 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002324 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002325 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002326 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002327 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2328 // Insert the new, smaller add.
2329 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2330 CI, "addconv");
2331 InsertNewInstBefore(NewAdd, I);
2332 return new SExtInst(NewAdd, I.getType());
2333 }
2334 }
2335
2336 // (add (sext x), (sext y)) --> (sext (add int x, y))
2337 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2338 // Only do this if x/y have the same type, if at last one of them has a
2339 // single use (so we don't increase the number of sexts), and if the
2340 // integer add will not overflow.
2341 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2342 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2343 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2344 RHSConv->getOperand(0))) {
2345 // Insert the new integer add.
2346 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2347 RHSConv->getOperand(0),
2348 "addconv");
2349 InsertNewInstBefore(NewAdd, I);
2350 return new SExtInst(NewAdd, I.getType());
2351 }
2352 }
2353 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002354
2355 return Changed ? &I : 0;
2356}
2357
2358Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2359 bool Changed = SimplifyCommutative(I);
2360 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2361
2362 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2363 // X + 0 --> X
2364 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002365 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002366 (I.getType())->getValueAPF()))
2367 return ReplaceInstUsesWith(I, LHS);
2368 }
2369
2370 if (isa<PHINode>(LHS))
2371 if (Instruction *NV = FoldOpIntoPhi(I))
2372 return NV;
2373 }
2374
2375 // -A + B --> B - A
2376 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002377 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002378 return BinaryOperator::CreateFSub(RHS, LHSV);
2379
2380 // A + -B --> A - B
2381 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002382 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002383 return BinaryOperator::CreateFSub(LHS, V);
2384
2385 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2387 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2388 return ReplaceInstUsesWith(I, LHS);
2389
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002390 // Check for (add double (sitofp x), y), see if we can merge this into an
2391 // integer add followed by a promotion.
2392 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2393 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2394 // ... if the constant fits in the integer value. This is useful for things
2395 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2396 // requires a constant pool load, and generally allows the add to be better
2397 // instcombined.
2398 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2399 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002400 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002401 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002402 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002403 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2404 // Insert the new integer add.
2405 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2406 CI, "addconv");
2407 InsertNewInstBefore(NewAdd, I);
2408 return new SIToFPInst(NewAdd, I.getType());
2409 }
2410 }
2411
2412 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2413 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2414 // Only do this if x/y have the same type, if at last one of them has a
2415 // single use (so we don't increase the number of int->fp conversions),
2416 // and if the integer add will not overflow.
2417 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2418 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2419 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2420 RHSConv->getOperand(0))) {
2421 // Insert the new integer add.
2422 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2423 RHSConv->getOperand(0),
2424 "addconv");
2425 InsertNewInstBefore(NewAdd, I);
2426 return new SIToFPInst(NewAdd, I.getType());
2427 }
2428 }
2429 }
2430
Chris Lattner7e708292002-06-25 16:13:24 +00002431 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002432}
2433
Chris Lattner7e708292002-06-25 16:13:24 +00002434Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002436
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002437 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002438 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002439
Chris Lattner233f7dc2002-08-12 21:17:25 +00002440 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002441 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002442 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002443
Chris Lattnere87597f2004-10-16 18:11:37 +00002444 if (isa<UndefValue>(Op0))
2445 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2446 if (isa<UndefValue>(Op1))
2447 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2448
Chris Lattnerd65460f2003-11-05 01:06:05 +00002449 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2450 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002451 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002452 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002453
Chris Lattnerd65460f2003-11-05 01:06:05 +00002454 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002455 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002456 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002457 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002458
Chris Lattner76b7a062007-01-15 07:02:54 +00002459 // -(X >>u 31) -> (X >>s 31)
2460 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002461 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002462 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002463 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002464 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002465 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002466 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002467 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002468 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002469 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002470 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002471 }
2472 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002473 }
2474 else if (SI->getOpcode() == Instruction::AShr) {
2475 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2476 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002477 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002478 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002479 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002480 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002481 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002482 }
2483 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002484 }
2485 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002486 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002487
2488 // Try to fold constant sub into select arguments.
2489 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002490 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002491 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002492
2493 // C - zext(bool) -> bool ? C - 1 : C
2494 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002495 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002496 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002497 }
2498
Owen Anderson1d0be152009-08-13 21:58:54 +00002499 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002500 return BinaryOperator::CreateXor(Op0, Op1);
2501
Chris Lattner43d84d62005-04-07 16:15:25 +00002502 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002503 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002504 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002505 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002506 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002507 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002508 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002509 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002510 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2511 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2512 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002513 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002514 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002515 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002516 }
2517
Chris Lattnerfd059242003-10-15 16:48:29 +00002518 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002519 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2520 // is not used by anyone else...
2521 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002522 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002523 // Swap the two operands of the subexpr...
2524 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2525 Op1I->setOperand(0, IIOp1);
2526 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002527
Chris Lattnera2881962003-02-18 19:28:33 +00002528 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002529 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002530 }
2531
2532 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2533 //
2534 if (Op1I->getOpcode() == Instruction::And &&
2535 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2536 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2537
Chris Lattnerf523d062004-06-09 05:08:07 +00002538 Value *NewNot =
Dan Gohman4ae51262009-08-12 16:23:25 +00002539 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002540 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002541 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002542
Reid Spencerac5209e2006-10-16 23:08:08 +00002543 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002544 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002545 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002546 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002547 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002548 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002549 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002550
Chris Lattnerad3448c2003-02-18 19:57:07 +00002551 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002552 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002553 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002554 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002555 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002556 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002558 }
Chris Lattner40371712002-05-09 01:29:19 +00002559 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002560 }
Chris Lattnera2881962003-02-18 19:28:33 +00002561
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002562 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2563 if (Op0I->getOpcode() == Instruction::Add) {
2564 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2565 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2566 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2567 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2568 } else if (Op0I->getOpcode() == Instruction::Sub) {
2569 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002570 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002571 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002572 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002574
Chris Lattner50af16a2004-11-13 19:50:12 +00002575 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002576 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002577 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002578 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002579
Chris Lattner50af16a2004-11-13 19:50:12 +00002580 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002581 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002582 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002583 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002584 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002585}
2586
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002587Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2589
2590 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002591 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 return BinaryOperator::CreateFAdd(Op0, V);
2593
2594 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2595 if (Op1I->getOpcode() == Instruction::FAdd) {
2596 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002597 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002598 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002599 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002600 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002601 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002602 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002603 }
2604
2605 return 0;
2606}
2607
Chris Lattnera0141b92007-07-15 20:42:37 +00002608/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2609/// comparison only checks the sign bit. If it only checks the sign bit, set
2610/// TrueIfSigned if the result of the comparison is true when the input value is
2611/// signed.
2612static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2613 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002614 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002615 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2616 TrueIfSigned = true;
2617 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002618 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2619 TrueIfSigned = true;
2620 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002621 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2622 TrueIfSigned = false;
2623 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002624 case ICmpInst::ICMP_UGT:
2625 // True if LHS u> RHS and RHS == high-bit-mask - 1
2626 TrueIfSigned = true;
2627 return RHS->getValue() ==
2628 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2629 case ICmpInst::ICMP_UGE:
2630 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2631 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002632 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002633 default:
2634 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002635 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002636}
2637
Chris Lattner7e708292002-06-25 16:13:24 +00002638Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002639 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002640 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002641
Eli Friedman1694e092009-07-18 09:12:15 +00002642 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002643 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002644
Chris Lattner233f7dc2002-08-12 21:17:25 +00002645 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002646 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2647 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002648
2649 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002650 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002651 if (SI->getOpcode() == Instruction::Shl)
2652 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002654 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002655
Zhou Sheng843f07672007-04-19 05:39:12 +00002656 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002657 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2658 if (CI->equalsInt(1)) // X * 1 == X
2659 return ReplaceInstUsesWith(I, Op0);
2660 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002661 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002662
Zhou Sheng97b52c22007-03-29 01:57:21 +00002663 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002664 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002665 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002666 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002667 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002668 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002669 if (Op1->isNullValue())
2670 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002671
2672 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2673 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002674 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002675
2676 // As above, vector X*splat(1.0) -> X in all defined cases.
2677 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002678 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2679 if (CI->equalsInt(1))
2680 return ReplaceInstUsesWith(I, Op0);
2681 }
2682 }
Chris Lattnera2881962003-02-18 19:28:33 +00002683 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002684
2685 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2686 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002687 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002688 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002689 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002690 Op1, "tmp");
2691 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002692 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002693 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002694 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002695
2696 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002697
2698 // Try to fold constant mul into select arguments.
2699 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002700 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002701 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002702
2703 if (isa<PHINode>(Op0))
2704 if (Instruction *NV = FoldOpIntoPhi(I))
2705 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002706 }
2707
Dan Gohman186a6362009-08-12 16:04:34 +00002708 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2709 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002710 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002711
Nick Lewycky0c730792008-11-21 07:33:58 +00002712 // (X / Y) * Y = X - (X % Y)
2713 // (X / Y) * -Y = (X % Y) - X
2714 {
2715 Value *Op1 = I.getOperand(1);
2716 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2717 if (!BO ||
2718 (BO->getOpcode() != Instruction::UDiv &&
2719 BO->getOpcode() != Instruction::SDiv)) {
2720 Op1 = Op0;
2721 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2722 }
Dan Gohman186a6362009-08-12 16:04:34 +00002723 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002724 if (BO && BO->hasOneUse() &&
2725 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2726 (BO->getOpcode() == Instruction::UDiv ||
2727 BO->getOpcode() == Instruction::SDiv)) {
2728 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2729
Dan Gohmanfa94b942009-08-12 16:33:09 +00002730 // If the division is exact, X % Y is zero.
2731 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2732 if (SDiv->isExact()) {
2733 if (Op1BO == Op1)
2734 return ReplaceInstUsesWith(I, Op0BO);
2735 else
2736 return BinaryOperator::CreateNeg(Op0BO);
2737 }
2738
Nick Lewycky0c730792008-11-21 07:33:58 +00002739 Instruction *Rem;
2740 if (BO->getOpcode() == Instruction::UDiv)
2741 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2742 else
2743 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2744
2745 InsertNewInstBefore(Rem, I);
2746 Rem->takeName(BO);
2747
2748 if (Op1BO == Op1)
2749 return BinaryOperator::CreateSub(Op0BO, Rem);
2750 else
2751 return BinaryOperator::CreateSub(Rem, Op0BO);
2752 }
2753 }
2754
Owen Anderson1d0be152009-08-13 21:58:54 +00002755 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002756 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2757
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002758 // If one of the operands of the multiply is a cast from a boolean value, then
2759 // we know the bool is either zero or one, so this is a 'masking' multiply.
2760 // See if we can simplify things based on how the boolean was originally
2761 // formed.
2762 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002763 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002764 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002765 BoolCast = CI;
2766 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002767 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002768 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002769 BoolCast = CI;
2770 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002771 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002772 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2773 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002774 bool TIS = false;
2775
Reid Spencere4d87aa2006-12-23 06:05:41 +00002776 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002777 // multiply into a shift/and combination.
2778 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002779 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2780 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002782 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002783 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002784 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002785 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002786 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002787 BoolCast->getOperand(0)->getName()+
2788 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002789
2790 // If the multiply type is not the same as the source type, sign extend
2791 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002792 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002793 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2794 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002795 Instruction::CastOps opcode =
2796 (SrcBits == DstBits ? Instruction::BitCast :
2797 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2798 V = InsertCastBefore(opcode, V, I.getType(), I);
2799 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002800
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002801 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002802 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002803 }
2804 }
2805 }
2806
Chris Lattner7e708292002-06-25 16:13:24 +00002807 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002808}
2809
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002810Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2811 bool Changed = SimplifyCommutative(I);
2812 Value *Op0 = I.getOperand(0);
2813
2814 // Simplify mul instructions with a constant RHS...
2815 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2816 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2817 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2818 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2819 if (Op1F->isExactlyValue(1.0))
2820 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2821 } else if (isa<VectorType>(Op1->getType())) {
2822 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2823 // As above, vector X*splat(1.0) -> X in all defined cases.
2824 if (Constant *Splat = Op1V->getSplatValue()) {
2825 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2826 if (F->isExactlyValue(1.0))
2827 return ReplaceInstUsesWith(I, Op0);
2828 }
2829 }
2830 }
2831
2832 // Try to fold constant mul into select arguments.
2833 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2834 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2835 return R;
2836
2837 if (isa<PHINode>(Op0))
2838 if (Instruction *NV = FoldOpIntoPhi(I))
2839 return NV;
2840 }
2841
Dan Gohman186a6362009-08-12 16:04:34 +00002842 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2843 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002844 return BinaryOperator::CreateFMul(Op0v, Op1v);
2845
2846 return Changed ? &I : 0;
2847}
2848
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002849/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2850/// instruction.
2851bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2852 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2853
2854 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2855 int NonNullOperand = -1;
2856 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2857 if (ST->isNullValue())
2858 NonNullOperand = 2;
2859 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2860 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2861 if (ST->isNullValue())
2862 NonNullOperand = 1;
2863
2864 if (NonNullOperand == -1)
2865 return false;
2866
2867 Value *SelectCond = SI->getOperand(0);
2868
2869 // Change the div/rem to use 'Y' instead of the select.
2870 I.setOperand(1, SI->getOperand(NonNullOperand));
2871
2872 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2873 // problem. However, the select, or the condition of the select may have
2874 // multiple uses. Based on our knowledge that the operand must be non-zero,
2875 // propagate the known value for the select into other uses of it, and
2876 // propagate a known value of the condition into its other users.
2877
2878 // If the select and condition only have a single use, don't bother with this,
2879 // early exit.
2880 if (SI->use_empty() && SelectCond->hasOneUse())
2881 return true;
2882
2883 // Scan the current block backward, looking for other uses of SI.
2884 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2885
2886 while (BBI != BBFront) {
2887 --BBI;
2888 // If we found a call to a function, we can't assume it will return, so
2889 // information from below it cannot be propagated above it.
2890 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2891 break;
2892
2893 // Replace uses of the select or its condition with the known values.
2894 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2895 I != E; ++I) {
2896 if (*I == SI) {
2897 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002898 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002899 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002900 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2901 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002902 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002903 }
2904 }
2905
2906 // If we past the instruction, quit looking for it.
2907 if (&*BBI == SI)
2908 SI = 0;
2909 if (&*BBI == SelectCond)
2910 SelectCond = 0;
2911
2912 // If we ran out of things to eliminate, break out of the loop.
2913 if (SelectCond == 0 && SI == 0)
2914 break;
2915
2916 }
2917 return true;
2918}
2919
2920
Reid Spencer1628cec2006-10-26 06:15:43 +00002921/// This function implements the transforms on div instructions that work
2922/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2923/// used by the visitors to those instructions.
2924/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002925Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002926 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002927
Chris Lattner50b2ca42008-02-19 06:12:18 +00002928 // undef / X -> 0 for integer.
2929 // undef / X -> undef for FP (the undef could be a snan).
2930 if (isa<UndefValue>(Op0)) {
2931 if (Op0->getType()->isFPOrFPVector())
2932 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002934 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002935
2936 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002937 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002938 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002939
Reid Spencer1628cec2006-10-26 06:15:43 +00002940 return 0;
2941}
Misha Brukmanfd939082005-04-21 23:48:37 +00002942
Reid Spencer1628cec2006-10-26 06:15:43 +00002943/// This function implements the transforms common to both integer division
2944/// instructions (udiv and sdiv). It is called by the visitors to those integer
2945/// division instructions.
2946/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002947Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002948 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2949
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002950 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002951 if (Op0 == Op1) {
2952 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002953 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002954 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002955 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002956 }
2957
Owen Andersoneed707b2009-07-24 23:12:02 +00002958 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002959 return ReplaceInstUsesWith(I, CI);
2960 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002961
Reid Spencer1628cec2006-10-26 06:15:43 +00002962 if (Instruction *Common = commonDivTransforms(I))
2963 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002964
2965 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2966 // This does not apply for fdiv.
2967 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2968 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002969
2970 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2971 // div X, 1 == X
2972 if (RHS->equalsInt(1))
2973 return ReplaceInstUsesWith(I, Op0);
2974
2975 // (X / C1) / C2 -> X / (C1*C2)
2976 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2977 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2978 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002979 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002980 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002981 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002982 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002983 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002984 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002985 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002986
Reid Spencerbca0e382007-03-23 20:05:17 +00002987 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002988 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2989 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2990 return R;
2991 if (isa<PHINode>(Op0))
2992 if (Instruction *NV = FoldOpIntoPhi(I))
2993 return NV;
2994 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002995 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002996
Chris Lattnera2881962003-02-18 19:28:33 +00002997 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002998 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002999 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003000 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003001
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003002 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003003 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003004 return ReplaceInstUsesWith(I, Op0);
3005
Nick Lewycky895f0852008-11-27 20:21:08 +00003006 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3007 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3008 // div X, 1 == X
3009 if (X->isOne())
3010 return ReplaceInstUsesWith(I, Op0);
3011 }
3012
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 return 0;
3014}
3015
3016Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3018
3019 // Handle the integer div common cases
3020 if (Instruction *Common = commonIDivTransforms(I))
3021 return Common;
3022
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003024 // X udiv C^2 -> X >> C
3025 // Check to see if this is an unsigned division with an exact power of 2,
3026 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003027 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003029 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003030
3031 // X udiv C, where C >= signbit
3032 if (C->getValue().isNegative()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003033 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003034 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003035 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003036 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003037 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003038 }
3039
3040 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003041 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 if (RHSI->getOpcode() == Instruction::Shl &&
3043 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003044 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003046 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003047 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003048 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003049 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003051 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003052 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003053 }
3054 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003055 }
3056
Reid Spencer1628cec2006-10-26 06:15:43 +00003057 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3058 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003059 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003061 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003062 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003063 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003064 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003065 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003066 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003067 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003068 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003069 Op0, TC, SI->getName()+".t");
3070 TSI = InsertNewInstBefore(TSI, I);
3071
3072 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003073 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003074 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003075 Op0, FC, SI->getName()+".f");
3076 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003077
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003078 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003079 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003080 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003081 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003082 return 0;
3083}
3084
Reid Spencer1628cec2006-10-26 06:15:43 +00003085Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3086 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3087
3088 // Handle the integer div common cases
3089 if (Instruction *Common = commonIDivTransforms(I))
3090 return Common;
3091
3092 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3093 // sdiv X, -1 == -X
3094 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003095 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003096
Dan Gohmanfa94b942009-08-12 16:33:09 +00003097 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003098 if (cast<SDivOperator>(&I)->isExact() &&
3099 RHS->getValue().isNonNegative() &&
3100 RHS->getValue().isPowerOf2()) {
3101 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3102 RHS->getValue().exactLogBase2());
3103 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3104 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003105
3106 // -X/C --> X/-C provided the negation doesn't overflow.
3107 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3108 if (isa<Constant>(Sub->getOperand(0)) &&
3109 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003110 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003111 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3112 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003113 }
3114
3115 // If the sign bits of both operands are zero (i.e. we can prove they are
3116 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003117 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003118 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003119 if (MaskedValueIsZero(Op0, Mask)) {
3120 if (MaskedValueIsZero(Op1, Mask)) {
3121 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3122 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3123 }
3124 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003125 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003126 ShiftedInt->getValue().isPowerOf2()) {
3127 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3128 // Safe because the only negative value (1 << Y) can take on is
3129 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3130 // the sign bit set.
3131 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3132 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003133 }
Eli Friedman8be17392009-07-18 09:53:21 +00003134 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003135
3136 return 0;
3137}
3138
3139Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3140 return commonDivTransforms(I);
3141}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003142
Reid Spencer0a783f72006-11-02 01:53:59 +00003143/// This function implements the transforms on rem instructions that work
3144/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3145/// is used by the visitors to those instructions.
3146/// @brief Transforms common to all three rem instructions
3147Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003149
Chris Lattner50b2ca42008-02-19 06:12:18 +00003150 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3151 if (I.getType()->isFPOrFPVector())
3152 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003153 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003154 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003155 if (isa<UndefValue>(Op1))
3156 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003157
3158 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003159 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3160 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003161
Reid Spencer0a783f72006-11-02 01:53:59 +00003162 return 0;
3163}
3164
3165/// This function implements the transforms common to both integer remainder
3166/// instructions (urem and srem). It is called by the visitors to those integer
3167/// remainder instructions.
3168/// @brief Common integer remainder transforms
3169Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172 if (Instruction *common = commonRemTransforms(I))
3173 return common;
3174
Dale Johannesened6af242009-01-21 00:35:19 +00003175 // 0 % X == 0 for integer, we don't need to preserve faults!
3176 if (Constant *LHS = dyn_cast<Constant>(Op0))
3177 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003178 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003179
Chris Lattner857e8cd2004-12-12 21:48:58 +00003180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003181 // X % 0 == undef, we don't need to preserve faults!
3182 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003183 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003184
Chris Lattnera2881962003-02-18 19:28:33 +00003185 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003186 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003187
Chris Lattner97943922006-02-28 05:49:21 +00003188 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3191 return R;
3192 } else if (isa<PHINode>(Op0I)) {
3193 if (Instruction *NV = FoldOpIntoPhi(I))
3194 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003195 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003196
3197 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003198 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003199 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003200 }
Chris Lattnera2881962003-02-18 19:28:33 +00003201 }
3202
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 return 0;
3204}
3205
3206Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3208
3209 if (Instruction *common = commonIRemTransforms(I))
3210 return common;
3211
3212 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3213 // X urem C^2 -> X and C
3214 // Check to see if this is an unsigned remainder with an exact power of 2,
3215 // if so, convert to a bitwise and.
3216 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003217 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003218 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 }
3220
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003221 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003222 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3223 if (RHSI->getOpcode() == Instruction::Shl &&
3224 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003225 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003226 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003227 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003228 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003229 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003230 }
3231 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003232 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003233
Reid Spencer0a783f72006-11-02 01:53:59 +00003234 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3235 // where C1&C2 are powers of two.
3236 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3237 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3238 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3239 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003240 if ((STO->getValue().isPowerOf2()) &&
3241 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 Value *TrueAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003243 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003244 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 Value *FalseAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003246 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003247 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003248 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 }
3250 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003251 }
3252
Chris Lattner3f5b8772002-05-06 16:14:14 +00003253 return 0;
3254}
3255
Reid Spencer0a783f72006-11-02 01:53:59 +00003256Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3258
Dan Gohmancff55092007-11-05 23:16:33 +00003259 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003260 if (Instruction *common = commonIRemTransforms(I))
3261 return common;
3262
Dan Gohman186a6362009-08-12 16:04:34 +00003263 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003264 if (!isa<Constant>(RHSNeg) ||
3265 (isa<ConstantInt>(RHSNeg) &&
3266 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003267 // X % -Y -> X % Y
3268 AddUsesToWorkList(I);
3269 I.setOperand(1, RHSNeg);
3270 return &I;
3271 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003272
Dan Gohmancff55092007-11-05 23:16:33 +00003273 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003275 if (I.getType()->isInteger()) {
3276 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3277 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3278 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003279 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003280 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 }
3282
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003283 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003284 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3285 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003286
Nick Lewycky9dce8732008-12-20 16:48:00 +00003287 bool hasNegative = false;
3288 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3289 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3290 if (RHS->getValue().isNegative())
3291 hasNegative = true;
3292
3293 if (hasNegative) {
3294 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003295 for (unsigned i = 0; i != VWidth; ++i) {
3296 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3297 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003298 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003299 else
3300 Elts[i] = RHS;
3301 }
3302 }
3303
Owen Andersonaf7ec972009-07-28 21:19:26 +00003304 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003305 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003306 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003307 I.setOperand(1, NewRHSV);
3308 return &I;
3309 }
3310 }
3311 }
3312
Reid Spencer0a783f72006-11-02 01:53:59 +00003313 return 0;
3314}
3315
3316Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003317 return commonRemTransforms(I);
3318}
3319
Chris Lattner457dd822004-06-09 07:59:58 +00003320// isOneBitSet - Return true if there is exactly one bit set in the specified
3321// constant.
3322static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003323 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003324}
3325
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003326// isHighOnes - Return true if the constant is of the form 1+0+.
3327// This is the same as lowones(~X).
3328static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003329 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003330}
3331
Reid Spencere4d87aa2006-12-23 06:05:41 +00003332/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003333/// are carefully arranged to allow folding of expressions such as:
3334///
3335/// (A < B) | (A > B) --> (A != B)
3336///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003337/// Note that this is only valid if the first and second predicates have the
3338/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003339///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003340/// Three bits are used to represent the condition, as follows:
3341/// 0 A > B
3342/// 1 A == B
3343/// 2 A < B
3344///
3345/// <=> Value Definition
3346/// 000 0 Always false
3347/// 001 1 A > B
3348/// 010 2 A == B
3349/// 011 3 A >= B
3350/// 100 4 A < B
3351/// 101 5 A != B
3352/// 110 6 A <= B
3353/// 111 7 Always true
3354///
3355static unsigned getICmpCode(const ICmpInst *ICI) {
3356 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003357 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003358 case ICmpInst::ICMP_UGT: return 1; // 001
3359 case ICmpInst::ICMP_SGT: return 1; // 001
3360 case ICmpInst::ICMP_EQ: return 2; // 010
3361 case ICmpInst::ICMP_UGE: return 3; // 011
3362 case ICmpInst::ICMP_SGE: return 3; // 011
3363 case ICmpInst::ICMP_ULT: return 4; // 100
3364 case ICmpInst::ICMP_SLT: return 4; // 100
3365 case ICmpInst::ICMP_NE: return 5; // 101
3366 case ICmpInst::ICMP_ULE: return 6; // 110
3367 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003368 // True -> 7
3369 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003370 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003371 return 0;
3372 }
3373}
3374
Evan Cheng8db90722008-10-14 17:15:11 +00003375/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3376/// predicate into a three bit mask. It also returns whether it is an ordered
3377/// predicate by reference.
3378static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3379 isOrdered = false;
3380 switch (CC) {
3381 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3382 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003383 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3384 case FCmpInst::FCMP_UGT: return 1; // 001
3385 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3386 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003387 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3388 case FCmpInst::FCMP_UGE: return 3; // 011
3389 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3390 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003391 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3392 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003393 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3394 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003395 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003396 default:
3397 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003398 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003399 return 0;
3400 }
3401}
3402
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403/// getICmpValue - This is the complement of getICmpCode, which turns an
3404/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003405/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003406/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003407static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003408 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003410 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003411 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003412 case 1:
3413 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003414 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003415 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003416 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3417 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003418 case 3:
3419 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003420 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003421 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003422 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 case 4:
3424 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003425 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003426 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3428 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429 case 6:
3430 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003432 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003433 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003434 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003435 }
3436}
3437
Evan Cheng8db90722008-10-14 17:15:11 +00003438/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3439/// opcode and two operands into either a FCmp instruction. isordered is passed
3440/// in to determine which kind of predicate to use in the new fcmp instruction.
3441static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003442 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003443 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003444 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003445 case 0:
3446 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003448 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003450 case 1:
3451 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003452 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003455 case 2:
3456 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003457 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003458 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003459 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003460 case 3:
3461 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003462 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003463 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003464 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003465 case 4:
3466 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003467 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003468 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003469 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003470 case 5:
3471 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003472 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003473 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003475 case 6:
3476 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003477 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003478 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003479 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003480 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003481 }
3482}
3483
Chris Lattnerb9553d62008-11-16 04:55:20 +00003484/// PredicatesFoldable - Return true if both predicates match sign or if at
3485/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3487 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003488 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3489 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490}
3491
3492namespace {
3493// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3494struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 InstCombiner &IC;
3496 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003497 ICmpInst::Predicate pred;
3498 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3499 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3500 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003502 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3503 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003504 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3505 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 return false;
3507 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003508 Instruction *apply(Instruction &Log) const {
3509 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3510 if (ICI->getOperand(0) != LHS) {
3511 assert(ICI->getOperand(1) == LHS);
3512 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003513 }
3514
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003515 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003516 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003517 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003518 unsigned Code;
3519 switch (Log.getOpcode()) {
3520 case Instruction::And: Code = LHSCode & RHSCode; break;
3521 case Instruction::Or: Code = LHSCode | RHSCode; break;
3522 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003523 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003524 }
3525
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003526 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3527 ICmpInst::isSignedPredicate(ICI->getPredicate());
3528
Owen Andersond672ecb2009-07-03 00:17:18 +00003529 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003530 if (Instruction *I = dyn_cast<Instruction>(RV))
3531 return I;
3532 // Otherwise, it's a constant boolean value...
3533 return IC.ReplaceInstUsesWith(Log, RV);
3534 }
3535};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003536} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003537
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3539// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003540// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003542 ConstantInt *OpRHS,
3543 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 BinaryOperator &TheAnd) {
3545 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003546 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003547 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003548 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003549
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 switch (Op->getOpcode()) {
3551 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003552 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003553 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003554 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003556 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003557 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003558 }
3559 break;
3560 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003561 if (Together == AndRHS) // (X | C) & C --> C
3562 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003563
Chris Lattner6e7ba452005-01-01 16:22:27 +00003564 if (Op->hasOneUse() && Together != OpRHS) {
3565 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003566 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003567 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003568 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003569 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 }
3571 break;
3572 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003573 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003574 // Adding a one to a single bit bit-field should be turned into an XOR
3575 // of the bit. First thing to check is to see if this AND is with a
3576 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003577 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578
3579 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003580 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003581 // Ok, at this point, we know that we are masking the result of the
3582 // ADD down to exactly one bit. If the constant we are adding has
3583 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003584 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003585
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003586 // Check to see if any bits below the one bit set in AndRHSV are set.
3587 if ((AddRHS & (AndRHSV-1)) == 0) {
3588 // If not, the only thing that can effect the output of the AND is
3589 // the bit specified by AndRHSV. If that bit is set, the effect of
3590 // the XOR is to toggle the bit. If it is clear, then the ADD has
3591 // no effect.
3592 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3593 TheAnd.setOperand(0, X);
3594 return &TheAnd;
3595 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003596 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003597 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003598 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003599 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003600 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003601 }
3602 }
3603 }
3604 }
3605 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003606
3607 case Instruction::Shl: {
3608 // We know that the AND will not produce any of the bits shifted in, so if
3609 // the anded constant includes them, clear them now!
3610 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003611 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003612 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003614 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003615
Zhou Sheng290bec52007-03-29 08:15:12 +00003616 if (CI->getValue() == ShlMask) {
3617 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003618 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3619 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003620 TheAnd.setOperand(1, CI);
3621 return &TheAnd;
3622 }
3623 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003624 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003625 case Instruction::LShr:
3626 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003627 // We know that the AND will not produce any of the bits shifted in, so if
3628 // the anded constant includes them, clear them now! This only applies to
3629 // unsigned shifts, because a signed shr may bring in set bits!
3630 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003631 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003632 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003633 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003634 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003635
Zhou Sheng290bec52007-03-29 08:15:12 +00003636 if (CI->getValue() == ShrMask) {
3637 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003638 return ReplaceInstUsesWith(TheAnd, Op);
3639 } else if (CI != AndRHS) {
3640 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3641 return &TheAnd;
3642 }
3643 break;
3644 }
3645 case Instruction::AShr:
3646 // Signed shr.
3647 // See if this is shifting in some sign extension, then masking it out
3648 // with an and.
3649 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003650 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003651 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003652 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003653 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003654 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003655 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003656 // Make the argument unsigned.
3657 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003658 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003659 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003660 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003661 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003662 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003663 }
3664 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003665 }
3666 return 0;
3667}
3668
Chris Lattner8b170942002-08-09 23:47:40 +00003669
Chris Lattnera96879a2004-09-29 17:40:11 +00003670/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3671/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3673/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003674/// insert new instructions.
3675Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 bool isSigned, bool Inside,
3677 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003678 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003679 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003680 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681
Chris Lattnera96879a2004-09-29 17:40:11 +00003682 if (Inside) {
3683 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003684 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003685
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003687 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003688 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003689 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003690 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003691 }
3692
3693 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003694 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003695 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003696 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003697 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003698 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003699 }
3700
3701 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003702 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003703
Reid Spencere4e40032007-03-21 23:19:50 +00003704 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003705 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003706 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 ICmpInst::Predicate pred = (isSigned ?
3708 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003709 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003711
Reid Spencere4e40032007-03-21 23:19:50 +00003712 // Emit V-Lo >u Hi-1-Lo
3713 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003714 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003715 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003716 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003717 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003718 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003719}
3720
Chris Lattner7203e152005-09-18 07:22:02 +00003721// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3722// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3723// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3724// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003725static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003726 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003727 uint32_t BitWidth = Val->getType()->getBitWidth();
3728 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003729
3730 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003731 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003732 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003733 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003734 return true;
3735}
3736
Chris Lattner7203e152005-09-18 07:22:02 +00003737/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3738/// where isSub determines whether the operator is a sub. If we can fold one of
3739/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740///
3741/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3742/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3743/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3744///
3745/// return (A +/- B).
3746///
3747Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003748 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003749 Instruction &I) {
3750 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3751 if (!LHSI || LHSI->getNumOperands() != 2 ||
3752 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3753
3754 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3755
3756 switch (LHSI->getOpcode()) {
3757 default: return 0;
3758 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003759 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003760 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003761 if ((Mask->getValue().countLeadingZeros() +
3762 Mask->getValue().countPopulation()) ==
3763 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003764 break;
3765
3766 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3767 // part, we don't need any explicit masks to take them out of A. If that
3768 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003769 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003770 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003771 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003772 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003773 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003774 break;
3775 }
3776 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003777 return 0;
3778 case Instruction::Or:
3779 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003780 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003781 if ((Mask->getValue().countLeadingZeros() +
3782 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003783 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003784 break;
3785 return 0;
3786 }
3787
3788 Instruction *New;
3789 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003790 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003791 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003792 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003793 return InsertNewInstBefore(New, I);
3794}
3795
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3797Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3798 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003799 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003800 ConstantInt *LHSCst, *RHSCst;
3801 ICmpInst::Predicate LHSCC, RHSCC;
3802
Chris Lattnerea065fb2008-11-16 05:10:52 +00003803 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003804 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003805 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003806 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003807 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003808 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003809
3810 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3811 // where C is a power of 2
3812 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3813 LHSCst->getValue().isPowerOf2()) {
3814 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3815 InsertNewInstBefore(NewOr, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003816 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003817 }
3818
3819 // From here on, we only handle:
3820 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3821 if (Val != Val2) return 0;
3822
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3824 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3825 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3826 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3827 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3828 return 0;
3829
3830 // We can't fold (ugt x, C) & (sgt x, C2).
3831 if (!PredicatesFoldable(LHSCC, RHSCC))
3832 return 0;
3833
3834 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003835 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 if (ICmpInst::isSignedPredicate(LHSCC) ||
3837 (ICmpInst::isEquality(LHSCC) &&
3838 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003839 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003841 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3842
3843 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 std::swap(LHS, RHS);
3845 std::swap(LHSCst, RHSCst);
3846 std::swap(LHSCC, RHSCC);
3847 }
3848
3849 // At this point, we know we have have two icmp instructions
3850 // comparing a value against two constants and and'ing the result
3851 // together. Because of the above check, we know that we only have
3852 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3853 // (from the FoldICmpLogical check above), that the two constants
3854 // are not equal and that the larger constant is on the RHS
3855 assert(LHSCst != RHSCst && "Compares not folded above?");
3856
3857 switch (LHSCC) {
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:
3860 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003861 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3863 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3864 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003865 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3867 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3868 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3869 return ReplaceInstUsesWith(I, LHS);
3870 }
3871 case ICmpInst::ICMP_NE:
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_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003875 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003876 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 break; // (X != 13 & X u< 15) -> no change
3878 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003879 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003880 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 break; // (X != 13 & X s< 15) -> no change
3882 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3883 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3884 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3885 return ReplaceInstUsesWith(I, RHS);
3886 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003887 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003888 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3890 Val->getName()+".off");
3891 InsertNewInstBefore(Add, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003892 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003893 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003894 }
3895 break; // (X != 13 & X != 15) -> no change
3896 }
3897 break;
3898 case ICmpInst::ICMP_ULT:
3899 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003900 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3902 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003903 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003904 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3905 break;
3906 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3907 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3908 return ReplaceInstUsesWith(I, LHS);
3909 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3910 break;
3911 }
3912 break;
3913 case ICmpInst::ICMP_SLT:
3914 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003915 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3917 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003918 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003919 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3920 break;
3921 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3922 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3923 return ReplaceInstUsesWith(I, LHS);
3924 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3925 break;
3926 }
3927 break;
3928 case ICmpInst::ICMP_UGT:
3929 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3932 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3933 return ReplaceInstUsesWith(I, RHS);
3934 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3935 break;
3936 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003937 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003938 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003939 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003940 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003941 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003942 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003943 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3944 break;
3945 }
3946 break;
3947 case ICmpInst::ICMP_SGT:
3948 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003949 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003950 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3951 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3952 return ReplaceInstUsesWith(I, RHS);
3953 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3954 break;
3955 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003956 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003957 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003958 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003959 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003960 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003961 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003962 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3963 break;
3964 }
3965 break;
3966 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003967
3968 return 0;
3969}
3970
Chris Lattner42d1be02009-07-23 05:14:02 +00003971Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3972 FCmpInst *RHS) {
3973
3974 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3975 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3976 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3977 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3978 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3979 // If either of the constants are nans, then the whole thing returns
3980 // false.
3981 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003982 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003983 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003984 LHS->getOperand(0), RHS->getOperand(0));
3985 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003986
3987 // Handle vector zeros. This occurs because the canonical form of
3988 // "fcmp ord x,x" is "fcmp ord x, 0".
3989 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3990 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003991 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003992 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003993 return 0;
3994 }
3995
3996 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3997 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3998 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3999
4000
4001 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4002 // Swap RHS operands to match LHS.
4003 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4004 std::swap(Op1LHS, Op1RHS);
4005 }
4006
4007 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4008 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4009 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004010 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004011
4012 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004013 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004014 if (Op0CC == FCmpInst::FCMP_TRUE)
4015 return ReplaceInstUsesWith(I, RHS);
4016 if (Op1CC == FCmpInst::FCMP_TRUE)
4017 return ReplaceInstUsesWith(I, LHS);
4018
4019 bool Op0Ordered;
4020 bool Op1Ordered;
4021 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4022 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4023 if (Op1Pred == 0) {
4024 std::swap(LHS, RHS);
4025 std::swap(Op0Pred, Op1Pred);
4026 std::swap(Op0Ordered, Op1Ordered);
4027 }
4028 if (Op0Pred == 0) {
4029 // uno && ueq -> uno && (uno || eq) -> ueq
4030 // ord && olt -> ord && (ord && lt) -> olt
4031 if (Op0Ordered == Op1Ordered)
4032 return ReplaceInstUsesWith(I, RHS);
4033
4034 // uno && oeq -> uno && (ord && eq) -> false
4035 // uno && ord -> false
4036 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004037 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004038 // ord && ueq -> ord && (uno || eq) -> oeq
4039 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4040 Op0LHS, Op0RHS, Context));
4041 }
4042 }
4043
4044 return 0;
4045}
4046
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004047
Chris Lattner7e708292002-06-25 16:13:24 +00004048Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004049 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004051
Chris Lattnere87597f2004-10-16 18:11:37 +00004052 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004054
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055 // and X, X = X
4056 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004057 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004058
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004059 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004060 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004061 if (SimplifyDemandedInstructionBits(I))
4062 return &I;
4063 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004064 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004065 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004066 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004067 } else if (isa<ConstantAggregateZero>(Op1)) {
4068 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004069 }
4070 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004071
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004072 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004073 const APInt& AndRHSMask = AndRHS->getValue();
4074 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004075
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004076 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004077 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004078 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004079 Value *Op0LHS = Op0I->getOperand(0);
4080 Value *Op0RHS = Op0I->getOperand(1);
4081 switch (Op0I->getOpcode()) {
4082 case Instruction::Xor:
4083 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004084 // If the mask is only needed on one incoming arm, push it up.
4085 if (Op0I->hasOneUse()) {
4086 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4087 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004088 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004089 Op0RHS->getName()+".masked");
4090 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004091 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004092 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004093 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004094 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004095 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4096 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004097 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004098 Op0LHS->getName()+".masked");
4099 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004100 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004101 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4102 }
4103 }
4104
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004106 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004107 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4108 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4109 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4110 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004111 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004112 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004113 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004114 break;
4115
4116 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004117 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4118 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4119 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4120 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004121 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004122
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004123 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4124 // has 1's for all bits that the subtraction with A might affect.
4125 if (Op0I->hasOneUse()) {
4126 uint32_t BitWidth = AndRHSMask.getBitWidth();
4127 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4128 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4129
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004130 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004131 if (!(A && A->isZero()) && // avoid infinite recursion.
4132 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohman4ae51262009-08-12 16:23:25 +00004133 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004134 InsertNewInstBefore(NewNeg, I);
4135 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4136 }
4137 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004138 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004139
4140 case Instruction::Shl:
4141 case Instruction::LShr:
4142 // (1 << x) & 1 --> zext(x == 0)
4143 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004144 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004145 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004146 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004147 InsertNewInstBefore(NewICmp, I);
4148 return new ZExtInst(NewICmp, I.getType());
4149 }
4150 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004151 }
4152
Chris Lattner58403262003-07-23 19:25:52 +00004153 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004154 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004155 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004156 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004157 // If this is an integer truncation or change from signed-to-unsigned, and
4158 // if the source is an and/or with immediate, transform it. This
4159 // frequently occurs for bitfield accesses.
4160 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004161 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004162 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004163 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004164 if (CastOp->getOpcode() == Instruction::And) {
4165 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004166 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4167 // This will fold the two constants together, which may allow
4168 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004169 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004170 CastOp->getOperand(0), I.getType(),
4171 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004172 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004173 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004174 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004175 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4176 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004177 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004178 } else if (CastOp->getOpcode() == Instruction::Or) {
4179 // Change: and (cast (or X, C1) to T), C2
4180 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004181 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004182 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4183 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004184 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004185 return ReplaceInstUsesWith(I, AndRHS);
4186 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004187 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004188 }
Chris Lattner06782f82003-07-23 19:36:21 +00004189 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004190
4191 // Try to fold constant and into select arguments.
4192 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004193 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004194 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004195 if (isa<PHINode>(Op0))
4196 if (Instruction *NV = FoldOpIntoPhi(I))
4197 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004198 }
4199
Dan Gohman186a6362009-08-12 16:04:34 +00004200 Value *Op0NotVal = dyn_castNotVal(Op0);
4201 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004202
Chris Lattner5b62aa72004-06-18 06:07:51 +00004203 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004204 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004205
Misha Brukmancb6267b2004-07-30 12:50:08 +00004206 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004207 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004208 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004209 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004210 InsertNewInstBefore(Or, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004211 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004212 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004213
4214 {
Chris Lattner003b6202007-06-15 05:58:24 +00004215 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004216 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004217 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4218 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004219
4220 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004221 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004222 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004223 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004224 }
4225 }
4226
Dan Gohman4ae51262009-08-12 16:23:25 +00004227 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004228 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4229 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004230
4231 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004232 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004233 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004234 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004235 }
4236 }
Chris Lattner64daab52006-04-01 08:03:55 +00004237
4238 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004239 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004240 if (A == Op1) { // (A^B)&A -> A&(A^B)
4241 I.swapOperands(); // Simplify below
4242 std::swap(Op0, Op1);
4243 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4244 cast<BinaryOperator>(Op0)->swapOperands();
4245 I.swapOperands(); // Simplify below
4246 std::swap(Op0, Op1);
4247 }
4248 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004249
Chris Lattner64daab52006-04-01 08:03:55 +00004250 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004251 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004252 if (B == Op0) { // B&(A^B) -> B&(B^A)
4253 cast<BinaryOperator>(Op1)->swapOperands();
4254 std::swap(A, B);
4255 }
4256 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00004257 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004258 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004259 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004260 }
4261 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004262
4263 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004264 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4265 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004266 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004267 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4268 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004269 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004270 }
4271
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4273 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004274 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004275 return R;
4276
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004277 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4278 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4279 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004280 }
4281
Chris Lattner6fc205f2006-05-05 06:39:07 +00004282 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004283 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4284 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4285 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4286 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004287 if (SrcTy == Op1C->getOperand(0)->getType() &&
4288 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004289 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4291 I.getType(), TD) &&
4292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4293 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004294 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004295 Op1C->getOperand(0),
4296 I.getName());
4297 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004298 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004299 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004300 }
Chris Lattnere511b742006-11-14 07:46:50 +00004301
4302 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004303 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4304 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4305 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004306 SI0->getOperand(1) == SI1->getOperand(1) &&
4307 (SI0->hasOneUse() || SI1->hasOneUse())) {
4308 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004309 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004310 SI1->getOperand(0),
4311 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004312 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004313 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004314 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004315 }
4316
Evan Cheng8db90722008-10-14 17:15:11 +00004317 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004318 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004319 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4320 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4321 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004322 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004323
Chris Lattner7e708292002-06-25 16:13:24 +00004324 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004325}
4326
Chris Lattner8c34cd22008-10-05 02:13:19 +00004327/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4328/// capable of providing pieces of a bswap. The subexpression provides pieces
4329/// of a bswap if it is proven that each of the non-zero bytes in the output of
4330/// the expression came from the corresponding "byte swapped" byte in some other
4331/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4332/// we know that the expression deposits the low byte of %X into the high byte
4333/// of the bswap result and that all other bytes are zero. This expression is
4334/// accepted, the high byte of ByteValues is set to X to indicate a correct
4335/// match.
4336///
4337/// This function returns true if the match was unsuccessful and false if so.
4338/// On entry to the function the "OverallLeftShift" is a signed integer value
4339/// indicating the number of bytes that the subexpression is later shifted. For
4340/// example, if the expression is later right shifted by 16 bits, the
4341/// OverallLeftShift value would be -2 on entry. This is used to specify which
4342/// byte of ByteValues is actually being set.
4343///
4344/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4345/// byte is masked to zero by a user. For example, in (X & 255), X will be
4346/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4347/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4348/// always in the local (OverallLeftShift) coordinate space.
4349///
4350static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4351 SmallVector<Value*, 8> &ByteValues) {
4352 if (Instruction *I = dyn_cast<Instruction>(V)) {
4353 // If this is an or instruction, it may be an inner node of the bswap.
4354 if (I->getOpcode() == Instruction::Or) {
4355 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4356 ByteValues) ||
4357 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4358 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004359 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004360
4361 // If this is a logical shift by a constant multiple of 8, recurse with
4362 // OverallLeftShift and ByteMask adjusted.
4363 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4364 unsigned ShAmt =
4365 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4366 // Ensure the shift amount is defined and of a byte value.
4367 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4368 return true;
4369
4370 unsigned ByteShift = ShAmt >> 3;
4371 if (I->getOpcode() == Instruction::Shl) {
4372 // X << 2 -> collect(X, +2)
4373 OverallLeftShift += ByteShift;
4374 ByteMask >>= ByteShift;
4375 } else {
4376 // X >>u 2 -> collect(X, -2)
4377 OverallLeftShift -= ByteShift;
4378 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004379 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004380 }
4381
4382 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4383 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4384
4385 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4386 ByteValues);
4387 }
4388
4389 // If this is a logical 'and' with a mask that clears bytes, clear the
4390 // corresponding bytes in ByteMask.
4391 if (I->getOpcode() == Instruction::And &&
4392 isa<ConstantInt>(I->getOperand(1))) {
4393 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4394 unsigned NumBytes = ByteValues.size();
4395 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4396 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4397
4398 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4399 // If this byte is masked out by a later operation, we don't care what
4400 // the and mask is.
4401 if ((ByteMask & (1 << i)) == 0)
4402 continue;
4403
4404 // If the AndMask is all zeros for this byte, clear the bit.
4405 APInt MaskB = AndMask & Byte;
4406 if (MaskB == 0) {
4407 ByteMask &= ~(1U << i);
4408 continue;
4409 }
4410
4411 // If the AndMask is not all ones for this byte, it's not a bytezap.
4412 if (MaskB != Byte)
4413 return true;
4414
4415 // Otherwise, this byte is kept.
4416 }
4417
4418 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4419 ByteValues);
4420 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004421 }
4422
Chris Lattner8c34cd22008-10-05 02:13:19 +00004423 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4424 // the input value to the bswap. Some observations: 1) if more than one byte
4425 // is demanded from this input, then it could not be successfully assembled
4426 // into a byteswap. At least one of the two bytes would not be aligned with
4427 // their ultimate destination.
4428 if (!isPowerOf2_32(ByteMask)) return true;
4429 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430
Chris Lattner8c34cd22008-10-05 02:13:19 +00004431 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4432 // is demanded, it needs to go into byte 0 of the result. This means that the
4433 // byte needs to be shifted until it lands in the right byte bucket. The
4434 // shift amount depends on the position: if the byte is coming from the high
4435 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4436 // low part, it must be shifted left.
4437 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4438 if (InputByteNo < ByteValues.size()/2) {
4439 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4440 return true;
4441 } else {
4442 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4443 return true;
4444 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004445
4446 // If the destination byte value is already defined, the values are or'd
4447 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004448 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004449 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004450 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004451 return false;
4452}
4453
4454/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4455/// If so, insert the new bswap intrinsic and return it.
4456Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004457 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004458 if (!ITy || ITy->getBitWidth() % 16 ||
4459 // ByteMask only allows up to 32-byte values.
4460 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004461 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004462
4463 /// ByteValues - For each byte of the result, we keep track of which value
4464 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004465 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004466 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467
4468 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004469 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4470 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004471 return 0;
4472
4473 // Check to see if all of the bytes come from the same value.
4474 Value *V = ByteValues[0];
4475 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4476
4477 // Check to make sure that all of the bytes come from the same value.
4478 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4479 if (ByteValues[i] != V)
4480 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004481 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004483 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004484 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004485}
4486
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004487/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4488/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4489/// we can simplify this expression to "cond ? C : D or B".
4490static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004491 Value *C, Value *D,
4492 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004493 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004494 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004495 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004496 return 0;
4497
Chris Lattnera6a474d2008-11-16 04:26:55 +00004498 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004499 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004500 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004501 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004502 return SelectInst::Create(Cond, C, B);
4503 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004504 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004505 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004506 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004507 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004508 return 0;
4509}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004510
Chris Lattner69d4ced2008-11-16 05:20:07 +00004511/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4512Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4513 ICmpInst *LHS, ICmpInst *RHS) {
4514 Value *Val, *Val2;
4515 ConstantInt *LHSCst, *RHSCst;
4516 ICmpInst::Predicate LHSCC, RHSCC;
4517
4518 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004519 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004520 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004521 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004522 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 return 0;
4524
4525 // From here on, we only handle:
4526 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4527 if (Val != Val2) return 0;
4528
4529 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4530 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4531 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4532 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4533 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4534 return 0;
4535
4536 // We can't fold (ugt x, C) | (sgt x, C2).
4537 if (!PredicatesFoldable(LHSCC, RHSCC))
4538 return 0;
4539
4540 // Ensure that the larger constant is on the RHS.
4541 bool ShouldSwap;
4542 if (ICmpInst::isSignedPredicate(LHSCC) ||
4543 (ICmpInst::isEquality(LHSCC) &&
4544 ICmpInst::isSignedPredicate(RHSCC)))
4545 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4546 else
4547 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4548
4549 if (ShouldSwap) {
4550 std::swap(LHS, RHS);
4551 std::swap(LHSCst, RHSCst);
4552 std::swap(LHSCC, RHSCC);
4553 }
4554
4555 // At this point, we know we have have two icmp instructions
4556 // comparing a value against two constants and or'ing the result
4557 // together. Because of the above check, we know that we only have
4558 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4559 // FoldICmpLogical check above), that the two constants are not
4560 // equal.
4561 assert(LHSCst != RHSCst && "Compares not folded above?");
4562
4563 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004564 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004565 case ICmpInst::ICMP_EQ:
4566 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004567 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004568 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004569 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004570 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004571 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004572 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4573 Val->getName()+".off");
4574 InsertNewInstBefore(Add, I);
Dan Gohman186a6362009-08-12 16:04:34 +00004575 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004576 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004577 }
4578 break; // (X == 13 | X == 15) -> no change
4579 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4580 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4581 break;
4582 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4583 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4584 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4585 return ReplaceInstUsesWith(I, RHS);
4586 }
4587 break;
4588 case ICmpInst::ICMP_NE:
4589 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004590 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004591 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4592 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4593 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4594 return ReplaceInstUsesWith(I, LHS);
4595 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4596 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4597 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004598 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004599 }
4600 break;
4601 case ICmpInst::ICMP_ULT:
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 == 14) -> no change
4605 break;
4606 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4607 // If RHSCst is [us]MAXINT, it is always false. Not handling
4608 // this can cause overflow.
4609 if (RHSCst->isMaxValue(false))
4610 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004611 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004612 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004613 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4614 break;
4615 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4616 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4617 return ReplaceInstUsesWith(I, RHS);
4618 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4619 break;
4620 }
4621 break;
4622 case ICmpInst::ICMP_SLT:
4623 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004624 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4626 break;
4627 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4628 // If RHSCst is [us]MAXINT, it is always false. Not handling
4629 // this can cause overflow.
4630 if (RHSCst->isMaxValue(true))
4631 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004632 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004633 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004634 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4635 break;
4636 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4637 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4638 return ReplaceInstUsesWith(I, RHS);
4639 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4640 break;
4641 }
4642 break;
4643 case ICmpInst::ICMP_UGT:
4644 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004645 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004646 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4647 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4648 return ReplaceInstUsesWith(I, LHS);
4649 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4650 break;
4651 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4652 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004653 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004654 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4655 break;
4656 }
4657 break;
4658 case ICmpInst::ICMP_SGT:
4659 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004660 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004661 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4662 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4663 return ReplaceInstUsesWith(I, LHS);
4664 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4665 break;
4666 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4667 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004668 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004669 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4670 break;
4671 }
4672 break;
4673 }
4674 return 0;
4675}
4676
Chris Lattner5414cc52009-07-23 05:46:22 +00004677Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4678 FCmpInst *RHS) {
4679 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4680 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4681 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4682 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4683 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4684 // If either of the constants are nans, then the whole thing returns
4685 // true.
4686 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004687 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004688
4689 // Otherwise, no need to compare the two constants, compare the
4690 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004691 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004692 LHS->getOperand(0), RHS->getOperand(0));
4693 }
4694
4695 // Handle vector zeros. This occurs because the canonical form of
4696 // "fcmp uno x,x" is "fcmp uno x, 0".
4697 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4698 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004699 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004700 LHS->getOperand(0), RHS->getOperand(0));
4701
4702 return 0;
4703 }
4704
4705 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4706 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4707 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4708
4709 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4710 // Swap RHS operands to match LHS.
4711 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4712 std::swap(Op1LHS, Op1RHS);
4713 }
4714 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4715 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4716 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004717 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004718 Op0LHS, Op0RHS);
4719 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004720 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004721 if (Op0CC == FCmpInst::FCMP_FALSE)
4722 return ReplaceInstUsesWith(I, RHS);
4723 if (Op1CC == FCmpInst::FCMP_FALSE)
4724 return ReplaceInstUsesWith(I, LHS);
4725 bool Op0Ordered;
4726 bool Op1Ordered;
4727 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4728 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4729 if (Op0Ordered == Op1Ordered) {
4730 // If both are ordered or unordered, return a new fcmp with
4731 // or'ed predicates.
4732 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4733 Op0LHS, Op0RHS, Context);
4734 if (Instruction *I = dyn_cast<Instruction>(RV))
4735 return I;
4736 // Otherwise, it's a constant boolean value...
4737 return ReplaceInstUsesWith(I, RV);
4738 }
4739 }
4740 return 0;
4741}
4742
Bill Wendlinga698a472008-12-01 08:23:25 +00004743/// FoldOrWithConstants - This helper function folds:
4744///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004745/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004746///
4747/// into:
4748///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004749/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004750///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004751/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004752Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004753 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004754 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4755 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004756
Bill Wendling286a0542008-12-02 06:24:20 +00004757 Value *V1 = 0;
4758 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004759 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004760
Bill Wendling29976b92008-12-02 06:18:11 +00004761 APInt Xor = CI1->getValue() ^ CI2->getValue();
4762 if (!Xor.isAllOnesValue()) return 0;
4763
Bill Wendling286a0542008-12-02 06:24:20 +00004764 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004765 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004766 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4767 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004768 }
4769
4770 return 0;
4771}
4772
Chris Lattner7e708292002-06-25 16:13:24 +00004773Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004774 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004775 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004776
Chris Lattner42593e62007-03-24 23:56:43 +00004777 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004778 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004779
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004780 // or X, X = X
4781 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004782 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004783
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004784 // See if we can simplify any instructions used by the instruction whose sole
4785 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004786 if (SimplifyDemandedInstructionBits(I))
4787 return &I;
4788 if (isa<VectorType>(I.getType())) {
4789 if (isa<ConstantAggregateZero>(Op1)) {
4790 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4791 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4792 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4793 return ReplaceInstUsesWith(I, I.getOperand(1));
4794 }
Chris Lattner42593e62007-03-24 23:56:43 +00004795 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004796
Chris Lattner3f5b8772002-05-06 16:14:14 +00004797 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004798 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004799 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004800 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004801 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004803 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004804 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004805 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004806 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004807 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004808 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004809
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004810 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004811 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004812 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004813 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004814 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004815 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004816 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004817 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004818 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004819
4820 // Try to fold constant and into select arguments.
4821 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004822 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004823 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004824 if (isa<PHINode>(Op0))
4825 if (Instruction *NV = FoldOpIntoPhi(I))
4826 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004827 }
4828
Chris Lattner4f637d42006-01-06 17:59:59 +00004829 Value *A = 0, *B = 0;
4830 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004831
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004833 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4834 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004835 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004836 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4837 return ReplaceInstUsesWith(I, Op0);
4838
Chris Lattner6423d4c2006-07-10 20:25:24 +00004839 // (A | B) | C and A | (B | C) -> bswap if possible.
4840 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4842 match(Op1, m_Or(m_Value(), m_Value())) ||
4843 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4844 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004845 if (Instruction *BSwap = MatchBSwap(I))
4846 return BSwap;
4847 }
4848
Chris Lattner6e4c6492005-05-09 04:58:36 +00004849 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004851 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004852 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004853 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004854 InsertNewInstBefore(NOr, I);
4855 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004856 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004857 }
4858
4859 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004860 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004861 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004862 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004863 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004864 InsertNewInstBefore(NOr, I);
4865 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004866 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004867 }
4868
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004869 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004870 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004871 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4872 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004873 Value *V1 = 0, *V2 = 0, *V3 = 0;
4874 C1 = dyn_cast<ConstantInt>(C);
4875 C2 = dyn_cast<ConstantInt>(D);
4876 if (C1 && C2) { // (A & C1)|(B & C2)
4877 // If we have: ((V + N) & C1) | (V & C2)
4878 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4879 // replace with V+N.
4880 if (C1->getValue() == ~C2->getValue()) {
4881 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004882 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004883 // Add commutes, try both ways.
4884 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4885 return ReplaceInstUsesWith(I, A);
4886 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4887 return ReplaceInstUsesWith(I, A);
4888 }
4889 // Or commutes, try both ways.
4890 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004891 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004892 // Add commutes, try both ways.
4893 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4894 return ReplaceInstUsesWith(I, B);
4895 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4896 return ReplaceInstUsesWith(I, B);
4897 }
4898 }
Chris Lattner044e5332007-04-08 08:01:49 +00004899 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004900 }
4901
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004902 // Check to see if we have any common things being and'ed. If so, find the
4903 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004904 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4905 if (A == B) // (A & C)|(A & D) == A & (C|D)
4906 V1 = A, V2 = C, V3 = D;
4907 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4908 V1 = A, V2 = B, V3 = C;
4909 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4910 V1 = C, V2 = A, V3 = D;
4911 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4912 V1 = C, V2 = A, V3 = B;
4913
4914 if (V1) {
4915 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004916 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4917 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004918 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004919 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004920
Dan Gohman1975d032008-10-30 20:40:10 +00004921 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004922 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004923 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004924 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004925 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004926 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004927 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004928 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004929 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004930
Bill Wendlingb01865c2008-11-30 13:52:49 +00004931 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004932 if ((match(C, m_Not(m_Specific(D))) &&
4933 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004934 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004935 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004936 if ((match(A, m_Not(m_Specific(D))) &&
4937 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004938 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004939 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004940 if ((match(C, m_Not(m_Specific(B))) &&
4941 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004942 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004943 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004944 if ((match(A, m_Not(m_Specific(B))) &&
4945 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004946 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004947 }
Chris Lattnere511b742006-11-14 07:46:50 +00004948
4949 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004950 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4951 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4952 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004953 SI0->getOperand(1) == SI1->getOperand(1) &&
4954 (SI0->hasOneUse() || SI1->hasOneUse())) {
4955 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004956 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004957 SI1->getOperand(0),
4958 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004959 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004960 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004961 }
4962 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004963
Bill Wendlingb3833d12008-12-01 01:07:11 +00004964 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004965 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4966 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004967 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004968 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004969 }
4970 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004971 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4972 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004973 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004974 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004975 }
4976
Dan Gohman4ae51262009-08-12 16:23:25 +00004977 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004978 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004979 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004980 } else {
4981 A = 0;
4982 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004983 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004984 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004985 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004986 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004987
Misha Brukmancb6267b2004-07-30 12:50:08 +00004988 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004989 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004990 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004991 I.getName()+".demorgan"), I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004992 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004993 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004994 }
Chris Lattnera2881962003-02-18 19:28:33 +00004995
Reid Spencere4d87aa2006-12-23 06:05:41 +00004996 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4997 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004998 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004999 return R;
5000
Chris Lattner69d4ced2008-11-16 05:20:07 +00005001 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5002 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5003 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005004 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005005
5006 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005007 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005008 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005009 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005010 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5011 !isa<ICmpInst>(Op1C->getOperand(0))) {
5012 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005013 if (SrcTy == Op1C->getOperand(0)->getType() &&
5014 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005015 // Only do this if the casts both really cause code to be
5016 // generated.
5017 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5018 I.getType(), TD) &&
5019 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5020 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005021 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00005022 Op1C->getOperand(0),
5023 I.getName());
5024 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005025 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005026 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005027 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005028 }
Chris Lattner99c65742007-10-24 05:38:08 +00005029 }
5030
5031
5032 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5033 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005034 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5035 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5036 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005037 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005038
Chris Lattner7e708292002-06-25 16:13:24 +00005039 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005040}
5041
Dan Gohman844731a2008-05-13 00:00:25 +00005042namespace {
5043
Chris Lattnerc317d392004-02-16 01:20:27 +00005044// XorSelf - Implements: X ^ X --> 0
5045struct XorSelf {
5046 Value *RHS;
5047 XorSelf(Value *rhs) : RHS(rhs) {}
5048 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5049 Instruction *apply(BinaryOperator &Xor) const {
5050 return &Xor;
5051 }
5052};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005053
Dan Gohman844731a2008-05-13 00:00:25 +00005054}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005055
Chris Lattner7e708292002-06-25 16:13:24 +00005056Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005057 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005059
Evan Chengd34af782008-03-25 20:07:13 +00005060 if (isa<UndefValue>(Op1)) {
5061 if (isa<UndefValue>(Op0))
5062 // Handle undef ^ undef -> 0 special case. This is a common
5063 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005064 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005065 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005066 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005067
Chris Lattnerc317d392004-02-16 01:20:27 +00005068 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005069 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005070 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005072 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005073
5074 // See if we can simplify any instructions used by the instruction whose sole
5075 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005076 if (SimplifyDemandedInstructionBits(I))
5077 return &I;
5078 if (isa<VectorType>(I.getType()))
5079 if (isa<ConstantAggregateZero>(Op1))
5080 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005081
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005082 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005083 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005084 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5085 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5086 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5087 if (Op0I->getOpcode() == Instruction::And ||
5088 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005089 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5090 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005091 Instruction *NotY =
Dan Gohman4ae51262009-08-12 16:23:25 +00005092 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005093 Op0I->getOperand(1)->getName()+".not");
5094 InsertNewInstBefore(NotY, I);
5095 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005096 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005097 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005098 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005099 }
5100 }
5101 }
5102 }
5103
5104
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005105 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005106 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005107 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005108 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005109 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005111
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005112 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005113 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005114 FCI->getOperand(0), FCI->getOperand(1));
5115 }
5116
Nick Lewycky517e1f52008-05-31 19:01:33 +00005117 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5118 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5119 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5120 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5121 Instruction::CastOps Opcode = Op0C->getOpcode();
5122 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005123 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005124 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005125 Op0C->getDestTy())) {
5126 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5127 CI->getOpcode(), CI->getInversePredicate(),
5128 CI->getOperand(0), CI->getOperand(1)), I);
5129 NewCI->takeName(CI);
5130 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5131 }
5132 }
5133 }
5134 }
5135 }
5136
Reid Spencere4d87aa2006-12-23 06:05:41 +00005137 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005138 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005139 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5140 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005141 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5142 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005143 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005144 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005145 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005146
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005147 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005148 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005149 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005150 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005151 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005152 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005153 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005154 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005155 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005156 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005157 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005158 Constant *C = ConstantInt::get(*Context,
5159 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005160 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005161
Chris Lattner7c4049c2004-01-12 19:35:11 +00005162 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005163 } else if (Op0I->getOpcode() == Instruction::Or) {
5164 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005165 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005166 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005167 // Anything in both C1 and C2 is known to be zero, remove it from
5168 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005169 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5170 NewRHS = ConstantExpr::getAnd(NewRHS,
5171 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005172 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005173 I.setOperand(0, Op0I->getOperand(0));
5174 I.setOperand(1, NewRHS);
5175 return &I;
5176 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005177 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005178 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005179 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005180
5181 // Try to fold constant and into select arguments.
5182 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005184 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005185 if (isa<PHINode>(Op0))
5186 if (Instruction *NV = FoldOpIntoPhi(I))
5187 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005188 }
5189
Dan Gohman186a6362009-08-12 16:04:34 +00005190 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005191 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005192 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005193
Dan Gohman186a6362009-08-12 16:04:34 +00005194 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005195 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005196 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005197
Chris Lattner318bf792007-03-18 22:51:34 +00005198
5199 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5200 if (Op1I) {
5201 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005202 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005203 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005204 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005205 I.swapOperands();
5206 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005207 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005208 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005209 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005210 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005211 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005212 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005213 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005214 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005215 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005216 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005217 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005218 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005219 std::swap(A, B);
5220 }
Chris Lattner318bf792007-03-18 22:51:34 +00005221 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005222 I.swapOperands(); // Simplified below.
5223 std::swap(Op0, Op1);
5224 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005225 }
Chris Lattner318bf792007-03-18 22:51:34 +00005226 }
5227
5228 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5229 if (Op0I) {
5230 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005231 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005232 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005233 if (A == Op1) // (B|A)^B == (A|B)^B
5234 std::swap(A, B);
5235 if (B == Op1) { // (A|B)^B == A & ~B
5236 Instruction *NotB =
Dan Gohman4ae51262009-08-12 16:23:25 +00005237 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005238 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005239 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005240 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005241 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005242 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005243 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005244 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005245 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005246 if (A == Op1) // (A&B)^A -> (B&A)^A
5247 std::swap(A, B);
5248 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005249 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005250 Instruction *N =
Dan Gohman4ae51262009-08-12 16:23:25 +00005251 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005252 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005253 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005254 }
Chris Lattner318bf792007-03-18 22:51:34 +00005255 }
5256
5257 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5258 if (Op0I && Op1I && Op0I->isShift() &&
5259 Op0I->getOpcode() == Op1I->getOpcode() &&
5260 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5261 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5262 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005263 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005264 Op1I->getOperand(0),
5265 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005266 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005267 Op1I->getOperand(1));
5268 }
5269
5270 if (Op0I && Op1I) {
5271 Value *A, *B, *C, *D;
5272 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005273 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5274 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005275 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005276 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005277 }
5278 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005279 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5280 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005281 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005282 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005283 }
5284
5285 // (A & B)^(C & D)
5286 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005287 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5288 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005289 // (X & Y)^(X & Y) -> (Y^Z) & X
5290 Value *X = 0, *Y = 0, *Z = 0;
5291 if (A == C)
5292 X = A, Y = B, Z = D;
5293 else if (A == D)
5294 X = A, Y = B, Z = C;
5295 else if (B == C)
5296 X = B, Y = A, Z = D;
5297 else if (B == D)
5298 X = B, Y = A, Z = C;
5299
5300 if (X) {
5301 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005302 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5303 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005304 }
5305 }
5306 }
5307
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5309 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005310 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005311 return R;
5312
Chris Lattner6fc205f2006-05-05 06:39:07 +00005313 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005314 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005315 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005316 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5317 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005318 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005319 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005320 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5321 I.getType(), TD) &&
5322 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5323 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005324 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005325 Op1C->getOperand(0),
5326 I.getName());
5327 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005328 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005329 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005330 }
Chris Lattner99c65742007-10-24 05:38:08 +00005331 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005332
Chris Lattner7e708292002-06-25 16:13:24 +00005333 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005334}
5335
Owen Andersond672ecb2009-07-03 00:17:18 +00005336static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005337 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005338 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005339}
Chris Lattnera96879a2004-09-29 17:40:11 +00005340
Dan Gohman6de29f82009-06-15 22:12:54 +00005341static bool HasAddOverflow(ConstantInt *Result,
5342 ConstantInt *In1, ConstantInt *In2,
5343 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005344 if (IsSigned)
5345 if (In2->getValue().isNegative())
5346 return Result->getValue().sgt(In1->getValue());
5347 else
5348 return Result->getValue().slt(In1->getValue());
5349 else
5350 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005351}
5352
Dan Gohman6de29f82009-06-15 22:12:54 +00005353/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005354/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005355static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005356 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005357 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005358 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005359
Dan Gohman6de29f82009-06-15 22:12:54 +00005360 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5361 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005362 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005363 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5364 ExtractElement(In1, Idx, Context),
5365 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005366 IsSigned))
5367 return true;
5368 }
5369 return false;
5370 }
5371
5372 return HasAddOverflow(cast<ConstantInt>(Result),
5373 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5374 IsSigned);
5375}
5376
5377static bool HasSubOverflow(ConstantInt *Result,
5378 ConstantInt *In1, ConstantInt *In2,
5379 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005380 if (IsSigned)
5381 if (In2->getValue().isNegative())
5382 return Result->getValue().slt(In1->getValue());
5383 else
5384 return Result->getValue().sgt(In1->getValue());
5385 else
5386 return Result->getValue().ugt(In1->getValue());
5387}
5388
Dan Gohman6de29f82009-06-15 22:12:54 +00005389/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5390/// overflowed for this type.
5391static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005392 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005393 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005394 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005395
5396 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5397 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005398 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005399 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5400 ExtractElement(In1, Idx, Context),
5401 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005402 IsSigned))
5403 return true;
5404 }
5405 return false;
5406 }
5407
5408 return HasSubOverflow(cast<ConstantInt>(Result),
5409 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5410 IsSigned);
5411}
5412
Chris Lattner574da9b2005-01-13 20:14:25 +00005413/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5414/// code necessary to compute the offset from the base pointer (without adding
5415/// in the base pointer). Return the result as a signed integer of intptr size.
5416static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005417 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005418 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005419 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Anderson07cf79e2009-07-06 23:00:19 +00005420 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005421 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005422
5423 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005424 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005426
Gabor Greif177dd3f2008-06-12 21:37:33 +00005427 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5428 ++i, ++GTI) {
5429 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005430 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5432 if (OpC->isZero()) continue;
5433
5434 // Handle a struct index, which adds its field offset to the pointer.
5435 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5436 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5437
5438 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005439 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005440 ConstantInt::get(*Context,
5441 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005442 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005443 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005444 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005445 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005446 GEP->getName()+".offs"), I);
5447 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005448 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005449
Owen Andersoneed707b2009-07-24 23:12:02 +00005450 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005451 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005452 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5453 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005454 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005455 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005456 else {
5457 // Emit an add instruction.
5458 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005459 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005460 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005461 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005462 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005463 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005464 // Convert to correct type.
5465 if (Op->getType() != IntPtrTy) {
5466 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005467 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005468 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005469 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5470 true,
5471 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005472 }
5473 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005474 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005475 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005476 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005477 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005478 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005479 GEP->getName()+".idx"), I);
5480 }
5481
5482 // Emit an add instruction.
5483 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005484 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005485 cast<Constant>(Result));
5486 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005487 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005488 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005489 }
5490 return Result;
5491}
5492
Chris Lattner10c0d912008-04-22 02:53:33 +00005493
Dan Gohman8f080f02009-07-17 22:16:21 +00005494/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5495/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5496/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5497/// be complex, and scales are involved. The above expression would also be
5498/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5499/// This later form is less amenable to optimization though, and we are allowed
5500/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005501///
5502/// If we can't emit an optimized form for this expression, this returns null.
5503///
5504static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5505 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005506 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005507 gep_type_iterator GTI = gep_type_begin(GEP);
5508
5509 // Check to see if this gep only has a single variable index. If so, and if
5510 // any constant indices are a multiple of its scale, then we can compute this
5511 // in terms of the scale of the variable index. For example, if the GEP
5512 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5513 // because the expression will cross zero at the same point.
5514 unsigned i, e = GEP->getNumOperands();
5515 int64_t Offset = 0;
5516 for (i = 1; i != e; ++i, ++GTI) {
5517 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5518 // Compute the aggregate offset of constant indices.
5519 if (CI->isZero()) continue;
5520
5521 // Handle a struct index, which adds its field offset to the pointer.
5522 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5523 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5524 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005525 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005526 Offset += Size*CI->getSExtValue();
5527 }
5528 } else {
5529 // Found our variable index.
5530 break;
5531 }
5532 }
5533
5534 // If there are no variable indices, we must have a constant offset, just
5535 // evaluate it the general way.
5536 if (i == e) return 0;
5537
5538 Value *VariableIdx = GEP->getOperand(i);
5539 // Determine the scale factor of the variable element. For example, this is
5540 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005541 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005542
5543 // Verify that there are no other variable indices. If so, emit the hard way.
5544 for (++i, ++GTI; i != e; ++i, ++GTI) {
5545 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5546 if (!CI) return 0;
5547
5548 // Compute the aggregate offset of constant indices.
5549 if (CI->isZero()) continue;
5550
5551 // Handle a struct index, which adds its field offset to the pointer.
5552 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5553 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5554 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005555 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005556 Offset += Size*CI->getSExtValue();
5557 }
5558 }
5559
5560 // Okay, we know we have a single variable index, which must be a
5561 // pointer/array/vector index. If there is no offset, life is simple, return
5562 // the index.
5563 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5564 if (Offset == 0) {
5565 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5566 // we don't need to bother extending: the extension won't affect where the
5567 // computation crosses zero.
5568 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005569 VariableIdx = new TruncInst(VariableIdx,
5570 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005571 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005572 return VariableIdx;
5573 }
5574
5575 // Otherwise, there is an index. The computation we will do will be modulo
5576 // the pointer size, so get it.
5577 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5578
5579 Offset &= PtrSizeMask;
5580 VariableScale &= PtrSizeMask;
5581
5582 // To do this transformation, any constant index must be a multiple of the
5583 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5584 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5585 // multiple of the variable scale.
5586 int64_t NewOffs = Offset / (int64_t)VariableScale;
5587 if (Offset != NewOffs*(int64_t)VariableScale)
5588 return 0;
5589
5590 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005591 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005592 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005593 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005594 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005595 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005596 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005597 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005598}
5599
5600
Reid Spencere4d87aa2006-12-23 06:05:41 +00005601/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005602/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005603Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005604 ICmpInst::Predicate Cond,
5605 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005606 // Look through bitcasts.
5607 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5608 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005609
Chris Lattner574da9b2005-01-13 20:14:25 +00005610 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005611 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005612 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005613 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005614 // know pointers can't overflow since the gep is inbounds. See if we can
5615 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005616 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5617
5618 // If not, synthesize the offset the hard way.
5619 if (Offset == 0)
5620 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005621 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005622 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005623 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005624 // If the base pointers are different, but the indices are the same, just
5625 // compare the base pointer.
5626 if (PtrBase != GEPRHS->getOperand(0)) {
5627 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005628 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005629 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005630 if (IndicesTheSame)
5631 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5632 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5633 IndicesTheSame = false;
5634 break;
5635 }
5636
5637 // If all indices are the same, just compare the base pointers.
5638 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005639 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005640 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005641
5642 // Otherwise, the base pointers are different and the indices are
5643 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005644 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005645 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005646
Chris Lattnere9d782b2005-01-13 22:25:21 +00005647 // If one of the GEPs has all zero indices, recurse.
5648 bool AllZeros = true;
5649 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5650 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5651 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5652 AllZeros = false;
5653 break;
5654 }
5655 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005656 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5657 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005658
5659 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005660 AllZeros = true;
5661 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5662 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5663 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5664 AllZeros = false;
5665 break;
5666 }
5667 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005668 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005669
Chris Lattner4401c9c2005-01-14 00:20:05 +00005670 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5671 // If the GEPs only differ by one index, compare it.
5672 unsigned NumDifferences = 0; // Keep track of # differences.
5673 unsigned DiffOperand = 0; // The operand that differs.
5674 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5675 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005676 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5677 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005678 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005679 NumDifferences = 2;
5680 break;
5681 } else {
5682 if (NumDifferences++) break;
5683 DiffOperand = i;
5684 }
5685 }
5686
5687 if (NumDifferences == 0) // SAME GEP?
5688 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005689 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005690 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005691
Chris Lattner4401c9c2005-01-14 00:20:05 +00005692 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005693 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5694 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005695 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005696 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005697 }
5698 }
5699
Reid Spencere4d87aa2006-12-23 06:05:41 +00005700 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005701 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005702 if (TD &&
5703 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005704 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5705 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5706 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5707 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005708 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005709 }
5710 }
5711 return 0;
5712}
5713
Chris Lattnera5406232008-05-19 20:18:56 +00005714/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5715///
5716Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5717 Instruction *LHSI,
5718 Constant *RHSC) {
5719 if (!isa<ConstantFP>(RHSC)) return 0;
5720 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5721
5722 // Get the width of the mantissa. We don't want to hack on conversions that
5723 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005724 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005725 if (MantissaWidth == -1) return 0; // Unknown.
5726
5727 // Check to see that the input is converted from an integer type that is small
5728 // enough that preserves all bits. TODO: check here for "known" sign bits.
5729 // 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 +00005730 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005731
5732 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5734 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005735 ++InputSize;
5736
5737 // If the conversion would lose info, don't hack on this.
5738 if ((int)InputSize > MantissaWidth)
5739 return 0;
5740
5741 // Otherwise, we can potentially simplify the comparison. We know that it
5742 // will always come through as an integer value and we know the constant is
5743 // not a NAN (it would have been previously simplified).
5744 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5745
5746 ICmpInst::Predicate Pred;
5747 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005748 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005749 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 case FCmpInst::FCMP_OEQ:
5751 Pred = ICmpInst::ICMP_EQ;
5752 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005753 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005754 case FCmpInst::FCMP_OGT:
5755 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5756 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005757 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005758 case FCmpInst::FCMP_OGE:
5759 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5760 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005761 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005762 case FCmpInst::FCMP_OLT:
5763 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5764 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005765 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005766 case FCmpInst::FCMP_OLE:
5767 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5768 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005769 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005770 case FCmpInst::FCMP_ONE:
5771 Pred = ICmpInst::ICMP_NE;
5772 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005773 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005774 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005775 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005776 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005777 }
5778
5779 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5780
5781 // Now we know that the APFloat is a normal number, zero or inf.
5782
Chris Lattner85162782008-05-20 03:50:52 +00005783 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005784 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005785 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005786
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005787 if (!LHSUnsigned) {
5788 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5789 // and large values.
5790 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5791 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5792 APFloat::rmNearestTiesToEven);
5793 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5794 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5795 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005796 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5797 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005798 }
5799 } else {
5800 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5801 // +INF and large values.
5802 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5803 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5804 APFloat::rmNearestTiesToEven);
5805 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5806 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5807 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005808 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5809 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005810 }
Chris Lattnera5406232008-05-19 20:18:56 +00005811 }
5812
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005813 if (!LHSUnsigned) {
5814 // See if the RHS value is < SignedMin.
5815 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5816 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5817 APFloat::rmNearestTiesToEven);
5818 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5819 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5820 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005821 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5822 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005823 }
Chris Lattnera5406232008-05-19 20:18:56 +00005824 }
5825
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005826 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5827 // [0, UMAX], but it may still be fractional. See if it is fractional by
5828 // casting the FP value to the integer value and back, checking for equality.
5829 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005830 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005831 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5832 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005833 if (!RHS.isZero()) {
5834 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005835 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5836 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005837 if (!Equal) {
5838 // If we had a comparison against a fractional value, we have to adjust
5839 // the compare predicate and sometimes the value. RHSC is rounded towards
5840 // zero at this point.
5841 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005842 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005843 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005844 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005845 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005846 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005847 case ICmpInst::ICMP_ULE:
5848 // (float)int <= 4.4 --> int <= 4
5849 // (float)int <= -4.4 --> false
5850 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005852 break;
5853 case ICmpInst::ICMP_SLE:
5854 // (float)int <= 4.4 --> int <= 4
5855 // (float)int <= -4.4 --> int < -4
5856 if (RHS.isNegative())
5857 Pred = ICmpInst::ICMP_SLT;
5858 break;
5859 case ICmpInst::ICMP_ULT:
5860 // (float)int < -4.4 --> false
5861 // (float)int < 4.4 --> int <= 4
5862 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005863 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005864 Pred = ICmpInst::ICMP_ULE;
5865 break;
5866 case ICmpInst::ICMP_SLT:
5867 // (float)int < -4.4 --> int < -4
5868 // (float)int < 4.4 --> int <= 4
5869 if (!RHS.isNegative())
5870 Pred = ICmpInst::ICMP_SLE;
5871 break;
5872 case ICmpInst::ICMP_UGT:
5873 // (float)int > 4.4 --> int > 4
5874 // (float)int > -4.4 --> true
5875 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005876 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005877 break;
5878 case ICmpInst::ICMP_SGT:
5879 // (float)int > 4.4 --> int > 4
5880 // (float)int > -4.4 --> int >= -4
5881 if (RHS.isNegative())
5882 Pred = ICmpInst::ICMP_SGE;
5883 break;
5884 case ICmpInst::ICMP_UGE:
5885 // (float)int >= -4.4 --> true
5886 // (float)int >= 4.4 --> int > 4
5887 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005889 Pred = ICmpInst::ICMP_UGT;
5890 break;
5891 case ICmpInst::ICMP_SGE:
5892 // (float)int >= -4.4 --> int >= -4
5893 // (float)int >= 4.4 --> int > 4
5894 if (!RHS.isNegative())
5895 Pred = ICmpInst::ICMP_SGT;
5896 break;
5897 }
Chris Lattnera5406232008-05-19 20:18:56 +00005898 }
5899 }
5900
5901 // Lower this FP comparison into an appropriate integer version of the
5902 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005903 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005904}
5905
Reid Spencere4d87aa2006-12-23 06:05:41 +00005906Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5907 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005908 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005909
Chris Lattner58e97462007-01-14 19:42:17 +00005910 // Fold trivial predicates.
5911 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005912 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005913 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005915
5916 // Simplify 'fcmp pred X, X'
5917 if (Op0 == Op1) {
5918 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005919 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005920 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5921 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5922 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005923 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005924 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5925 case FCmpInst::FCMP_OLT: // True if ordered and less than
5926 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005927 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005928
5929 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5930 case FCmpInst::FCMP_ULT: // True if unordered or less than
5931 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5932 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5933 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5934 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005935 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005936 return &I;
5937
5938 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5939 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5940 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5941 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5942 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5943 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005944 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005945 return &I;
5946 }
5947 }
5948
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005950 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005951
Reid Spencere4d87aa2006-12-23 06:05:41 +00005952 // Handle fcmp with constant RHS
5953 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005954 // If the constant is a nan, see if we can fold the comparison based on it.
5955 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5956 if (CFP->getValueAPF().isNaN()) {
5957 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005959 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5960 "Comparison must be either ordered or unordered!");
5961 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005962 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005963 }
5964 }
5965
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5967 switch (LHSI->getOpcode()) {
5968 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005969 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5970 // block. If in the same block, we're encouraging jump threading. If
5971 // not, we are just pessimizing the code by making an i1 phi.
5972 if (LHSI->getParent() == I.getParent())
5973 if (Instruction *NV = FoldOpIntoPhi(I))
5974 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005976 case Instruction::SIToFP:
5977 case Instruction::UIToFP:
5978 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5979 return NV;
5980 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981 case Instruction::Select:
5982 // If either operand of the select is a constant, we can fold the
5983 // comparison into the select arms, which will cause one to be
5984 // constant folded and the select turned into a bitwise or.
5985 Value *Op1 = 0, *Op2 = 0;
5986 if (LHSI->hasOneUse()) {
5987 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5988 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005989 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005991 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992 LHSI->getOperand(2), RHSC,
5993 I.getName()), I);
5994 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5995 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005996 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005998 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005999 LHSI->getOperand(1), RHSC,
6000 I.getName()), I);
6001 }
6002 }
6003
6004 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006005 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 break;
6007 }
6008 }
6009
6010 return Changed ? &I : 0;
6011}
6012
6013Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6014 bool Changed = SimplifyCompare(I);
6015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6016 const Type *Ty = Op0->getType();
6017
6018 // icmp X, X
6019 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00006020 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006021 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006022
6023 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00006024 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006025
Reid Spencere4d87aa2006-12-23 06:05:41 +00006026 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006027 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00006028 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6029 isa<ConstantPointerNull>(Op0)) &&
6030 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006031 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006032 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006033 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006034
Reid Spencere4d87aa2006-12-23 06:05:41 +00006035 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006036 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006037 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006038 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006039 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006040 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006041 InsertNewInstBefore(Xor, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00006042 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006043 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006044 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006045 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006046
Reid Spencere4d87aa2006-12-23 06:05:41 +00006047 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006048 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006049 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006050 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohman4ae51262009-08-12 16:23:25 +00006051 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006052 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006053 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006054 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006055 case ICmpInst::ICMP_SGT:
6056 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006057 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006058 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006059 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006060 InsertNewInstBefore(Not, I);
6061 return BinaryOperator::CreateAnd(Not, Op0);
6062 }
6063 case ICmpInst::ICMP_UGE:
6064 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6065 // FALL THROUGH
6066 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohman4ae51262009-08-12 16:23:25 +00006067 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006068 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006069 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006070 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006071 case ICmpInst::ICMP_SGE:
6072 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6073 // FALL THROUGH
6074 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006075 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006076 InsertNewInstBefore(Not, I);
6077 return BinaryOperator::CreateOr(Not, Op0);
6078 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006079 }
Chris Lattner8b170942002-08-09 23:47:40 +00006080 }
6081
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082 unsigned BitWidth = 0;
6083 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006084 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6085 else if (Ty->isIntOrIntVector())
6086 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087
6088 bool isSignBit = false;
6089
Dan Gohman81b28ce2008-09-16 18:46:06 +00006090 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006091 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006092 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006093
Chris Lattnerb6566012008-01-05 01:18:20 +00006094 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6095 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006096 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006097 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006098 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006099 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006100
Dan Gohman81b28ce2008-09-16 18:46:06 +00006101 // If we have an icmp le or icmp ge instruction, turn it into the
6102 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6103 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006104 switch (I.getPredicate()) {
6105 default: break;
6106 case ICmpInst::ICMP_ULE:
6107 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006108 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006109 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006110 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006111 case ICmpInst::ICMP_SLE:
6112 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006113 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006114 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006115 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006116 case ICmpInst::ICMP_UGE:
6117 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006119 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006120 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006121 case ICmpInst::ICMP_SGE:
6122 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006123 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006124 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006125 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006126 }
6127
Chris Lattner183661e2008-07-11 05:40:05 +00006128 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006129 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006130 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006131 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6132 }
6133
6134 // See if we can fold the comparison based on range information we can get
6135 // by checking whether bits are known to be zero or one in the input.
6136 if (BitWidth != 0) {
6137 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6138 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6139
6140 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006141 isSignBit ? APInt::getSignBit(BitWidth)
6142 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006144 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (SimplifyDemandedBits(I.getOperandUse(1),
6146 APInt::getAllOnesValue(BitWidth),
6147 Op1KnownZero, Op1KnownOne, 0))
6148 return &I;
6149
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006150 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006151 // in. Compute the Min, Max and RHS values based on the known bits. For the
6152 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6154 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6155 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6156 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6157 Op0Min, Op0Max);
6158 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6159 Op1Min, Op1Max);
6160 } else {
6161 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6162 Op0Min, Op0Max);
6163 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6164 Op1Min, Op1Max);
6165 }
6166
Chris Lattner183661e2008-07-11 05:40:05 +00006167 // If Min and Max are known to be the same, then SimplifyDemandedBits
6168 // figured out that the LHS is a constant. Just constant fold this now so
6169 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006171 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006172 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006174 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006175 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176
Chris Lattner183661e2008-07-11 05:40:05 +00006177 // Based on the range information we know about the LHS, see if we can
6178 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006180 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006181 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006183 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006184 break;
6185 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006187 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006188 break;
6189 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006191 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006193 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006195 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6197 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006198 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006199 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200
6201 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6202 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006203 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006204 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 }
Chris Lattner84dff672008-07-11 05:08:55 +00006206 break;
6207 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006209 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006211 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212
6213 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006214 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6216 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006217 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006218 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219
6220 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6221 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006222 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006223 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 }
Chris Lattner84dff672008-07-11 05:08:55 +00006225 break;
6226 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006227 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006228 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006232 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6234 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006235 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006236 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006237 }
Chris Lattner84dff672008-07-11 05:08:55 +00006238 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006239 case ICmpInst::ICMP_SGT:
6240 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006241 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006242 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006243 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006244
6245 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006246 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006247 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6248 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006249 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006250 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251 }
6252 break;
6253 case ICmpInst::ICMP_SGE:
6254 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6255 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006256 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006257 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006258 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006259 break;
6260 case ICmpInst::ICMP_SLE:
6261 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6262 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006263 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006264 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006265 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006266 break;
6267 case ICmpInst::ICMP_UGE:
6268 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6269 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006270 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006271 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006272 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006273 break;
6274 case ICmpInst::ICMP_ULE:
6275 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6276 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006277 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006278 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006279 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006280 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006281 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006282
6283 // Turn a signed comparison into an unsigned one if both operands
6284 // are known to have the same sign.
6285 if (I.isSignedPredicate() &&
6286 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6287 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006288 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006289 }
6290
6291 // Test if the ICmpInst instruction is used exclusively by a select as
6292 // part of a minimum or maximum operation. If so, refrain from doing
6293 // any other folding. This helps out other analyses which understand
6294 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6295 // and CodeGen. And in this case, at least one of the comparison
6296 // operands has at least one user besides the compare (the select),
6297 // which would often largely negate the benefit of folding anyway.
6298 if (I.hasOneUse())
6299 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6300 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6301 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6302 return 0;
6303
6304 // See if we are doing a comparison between a constant and an instruction that
6305 // can be folded into the comparison.
6306 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006307 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006308 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006309 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006310 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006311 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6312 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006313 }
6314
Chris Lattner01deb9d2007-04-03 17:43:25 +00006315 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006316 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6317 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6318 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006319 case Instruction::GetElementPtr:
6320 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006322 bool isAllZeros = true;
6323 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6324 if (!isa<Constant>(LHSI->getOperand(i)) ||
6325 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6326 isAllZeros = false;
6327 break;
6328 }
6329 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006330 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006331 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006332 }
6333 break;
6334
Chris Lattner6970b662005-04-23 15:31:55 +00006335 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006336 // Only fold icmp into the PHI if the phi and fcmp are in the same
6337 // block. If in the same block, we're encouraging jump threading. If
6338 // not, we are just pessimizing the code by making an i1 phi.
6339 if (LHSI->getParent() == I.getParent())
6340 if (Instruction *NV = FoldOpIntoPhi(I))
6341 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006342 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006343 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006344 // If either operand of the select is a constant, we can fold the
6345 // comparison into the select arms, which will cause one to be
6346 // constant folded and the select turned into a bitwise or.
6347 Value *Op1 = 0, *Op2 = 0;
6348 if (LHSI->hasOneUse()) {
6349 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6350 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006351 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006352 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006353 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006354 LHSI->getOperand(2), RHSC,
6355 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006356 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6357 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006358 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006360 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006361 LHSI->getOperand(1), RHSC,
6362 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006363 }
6364 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006365
Chris Lattner6970b662005-04-23 15:31:55 +00006366 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006367 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006368 break;
6369 }
Chris Lattner4802d902007-04-06 18:57:34 +00006370 case Instruction::Malloc:
6371 // If we have (malloc != null), and if the malloc has a single use, we
6372 // can assume it is successful and remove the malloc.
6373 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006374 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006375 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006376 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006377 }
6378 break;
6379 }
Chris Lattner6970b662005-04-23 15:31:55 +00006380 }
6381
Reid Spencere4d87aa2006-12-23 06:05:41 +00006382 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006383 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006384 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006385 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006386 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006387 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6388 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006389 return NI;
6390
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006392 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6393 // now.
6394 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6395 if (isa<PointerType>(Op0->getType()) &&
6396 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006397 // We keep moving the cast from the left operand over to the right
6398 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006399 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006400
Chris Lattner57d86372007-01-06 01:45:59 +00006401 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6402 // so eliminate it as well.
6403 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6404 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006405
Chris Lattnerde90b762003-11-03 04:25:02 +00006406 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006407 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006408 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006409 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006410 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006411 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006412 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006413 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006414 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006415 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006416 }
Chris Lattner57d86372007-01-06 01:45:59 +00006417 }
6418
6419 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006420 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006421 // This comes up when you have code like
6422 // int X = A < B;
6423 // if (X) ...
6424 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006425 // with a constant or another cast from the same type.
6426 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006427 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006428 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006429 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006430
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006431 // See if it's the same type of instruction on the left and right.
6432 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6433 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006434 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006435 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006436 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006437 default: break;
6438 case Instruction::Add:
6439 case Instruction::Sub:
6440 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006441 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006442 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006443 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006444 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6445 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6446 if (CI->getValue().isSignBit()) {
6447 ICmpInst::Predicate Pred = I.isSignedPredicate()
6448 ? I.getUnsignedPredicate()
6449 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006450 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006451 Op1I->getOperand(0));
6452 }
6453
6454 if (CI->getValue().isMaxSignedValue()) {
6455 ICmpInst::Predicate Pred = I.isSignedPredicate()
6456 ? I.getUnsignedPredicate()
6457 : I.getSignedPredicate();
6458 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006459 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006460 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006461 }
6462 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006463 break;
6464 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006465 if (!I.isEquality())
6466 break;
6467
Nick Lewycky5d52c452008-08-21 05:56:10 +00006468 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6469 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6470 // Mask = -1 >> count-trailing-zeros(Cst).
6471 if (!CI->isZero() && !CI->isOne()) {
6472 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006473 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006474 APInt::getLowBitsSet(AP.getBitWidth(),
6475 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006476 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006477 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6478 Mask);
6479 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6480 Mask);
6481 InsertNewInstBefore(And1, I);
6482 InsertNewInstBefore(And2, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006483 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006484 }
6485 }
6486 break;
6487 }
6488 }
6489 }
6490 }
6491
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006492 // ~x < ~y --> y < x
6493 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006494 if (match(Op0, m_Not(m_Value(A))) &&
6495 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006496 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006497 }
6498
Chris Lattner65b72ba2006-09-18 04:22:48 +00006499 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006500 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006501
6502 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006503 if (match(Op0, m_Neg(m_Value(A))) &&
6504 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006505 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006506
Dan Gohman4ae51262009-08-12 16:23:25 +00006507 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006508 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6509 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006510 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006511 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006512 }
6513
Dan Gohman4ae51262009-08-12 16:23:25 +00006514 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006515 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006516 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006517 if (match(B, m_ConstantInt(C1)) &&
6518 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006519 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006520 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006521 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006522 return new ICmpInst(I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006523 InsertNewInstBefore(Xor, I));
6524 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006525
6526 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006527 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6528 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6529 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6530 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006531 }
6532 }
6533
Dan Gohman4ae51262009-08-12 16:23:25 +00006534 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006535 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006536 // A == (A^B) -> B == 0
6537 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006538 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006539 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006540 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006541
6542 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006543 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006544 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006545 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006546
6547 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006548 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006549 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006550 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006551
Chris Lattner9c2328e2006-11-14 06:06:06 +00006552 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6553 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006554 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6555 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006556 Value *X = 0, *Y = 0, *Z = 0;
6557
6558 if (A == C) {
6559 X = B; Y = D; Z = A;
6560 } else if (A == D) {
6561 X = B; Y = C; Z = A;
6562 } else if (B == C) {
6563 X = A; Y = D; Z = B;
6564 } else if (B == D) {
6565 X = A; Y = C; Z = B;
6566 }
6567
6568 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006569 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6570 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006571 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006572 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006573 return &I;
6574 }
6575 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006576 }
Chris Lattner7e708292002-06-25 16:13:24 +00006577 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006578}
6579
Chris Lattner562ef782007-06-20 23:46:26 +00006580
6581/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6582/// and CmpRHS are both known to be integer constants.
6583Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6584 ConstantInt *DivRHS) {
6585 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6586 const APInt &CmpRHSV = CmpRHS->getValue();
6587
6588 // FIXME: If the operand types don't match the type of the divide
6589 // then don't attempt this transform. The code below doesn't have the
6590 // logic to deal with a signed divide and an unsigned compare (and
6591 // vice versa). This is because (x /s C1) <s C2 produces different
6592 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6593 // (x /u C1) <u C2. Simply casting the operands and result won't
6594 // work. :( The if statement below tests that condition and bails
6595 // if it finds it.
6596 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6597 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6598 return 0;
6599 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006601 if (DivIsSigned && DivRHS->isAllOnesValue())
6602 return 0; // The overflow computation also screws up here
6603 if (DivRHS->isOne())
6604 return 0; // Not worth bothering, and eliminates some funny cases
6605 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006606
6607 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6608 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6609 // C2 (CI). By solving for X we can turn this into a range check
6610 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006611 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006612
6613 // Determine if the product overflows by seeing if the product is
6614 // not equal to the divide. Make sure we do the same kind of divide
6615 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006616 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6617 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006618
6619 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006620 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006621
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 // Figure out the interval that is being checked. For example, a comparison
6623 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6624 // Compute this interval based on the constants involved and the signedness of
6625 // the compare/divide. This computes a half-open interval, keeping track of
6626 // whether either value in the interval overflows. After analysis each
6627 // overflow variable is set to 0 if it's corresponding bound variable is valid
6628 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6629 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006630 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631
Chris Lattner562ef782007-06-20 23:46:26 +00006632 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006633 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006634 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006635 HiOverflow = LoOverflow = ProdOV;
6636 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006637 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006638 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006639 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006641 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006642 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006643 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006644 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6645 HiOverflow = LoOverflow = ProdOV;
6646 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006647 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006648 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006649 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006650 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006651 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6652 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006653 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006654 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006655 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006656 true) ? -1 : 0;
6657 }
Chris Lattner562ef782007-06-20 23:46:26 +00006658 }
Dan Gohman76491272008-02-13 22:09:18 +00006659 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006660 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006661 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006662 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006663 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6665 HiOverflow = 1; // [INTMIN+1, overflow)
6666 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6667 }
Dan Gohman76491272008-02-13 22:09:18 +00006668 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006670 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006672 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006673 LoOverflow = AddWithOverflow(LoBound, HiBound,
6674 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006675 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006676 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6677 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006678 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006679 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006680 }
6681
Chris Lattner1dbfd482007-06-21 18:11:19 +00006682 // Dividing by a negative swaps the condition. LT <-> GT
6683 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006684 }
6685
6686 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006687 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006688 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006689 case ICmpInst::ICMP_EQ:
6690 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006691 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006692 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006693 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006694 ICmpInst::ICMP_UGE, X, LoBound);
6695 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006696 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006697 ICmpInst::ICMP_ULT, X, HiBound);
6698 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006699 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006700 case ICmpInst::ICMP_NE:
6701 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006702 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006703 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006704 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006705 ICmpInst::ICMP_ULT, X, LoBound);
6706 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006707 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006708 ICmpInst::ICMP_UGE, X, HiBound);
6709 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006710 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006711 case ICmpInst::ICMP_ULT:
6712 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006713 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006714 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006715 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006716 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006717 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006718 case ICmpInst::ICMP_UGT:
6719 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006720 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006721 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006722 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006723 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006724 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006725 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006726 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006727 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006728 }
6729}
6730
6731
Chris Lattner01deb9d2007-04-03 17:43:25 +00006732/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6733///
6734Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6735 Instruction *LHSI,
6736 ConstantInt *RHS) {
6737 const APInt &RHSV = RHS->getValue();
6738
6739 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006740 case Instruction::Trunc:
6741 if (ICI.isEquality() && LHSI->hasOneUse()) {
6742 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6743 // of the high bits truncated out of x are known.
6744 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6745 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6746 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6747 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6748 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6749
6750 // If all the high bits are known, we can do this xform.
6751 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6752 // Pull in the high bits from known-ones set.
6753 APInt NewRHS(RHS->getValue());
6754 NewRHS.zext(SrcBits);
6755 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006756 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006757 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006758 }
6759 }
6760 break;
6761
Duncan Sands0091bf22007-04-04 06:42:45 +00006762 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006763 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6764 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6765 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006766 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6767 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006768 Value *CompareVal = LHSI->getOperand(0);
6769
6770 // If the sign bit of the XorCST is not set, there is no change to
6771 // the operation, just stop using the Xor.
6772 if (!XorCST->getValue().isNegative()) {
6773 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006774 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 return &ICI;
6776 }
6777
6778 // Was the old condition true if the operand is positive?
6779 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6780
6781 // If so, the new one isn't.
6782 isTrueIfPositive ^= true;
6783
6784 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006785 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006786 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006787 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006788 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006789 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006790 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006791
6792 if (LHSI->hasOneUse()) {
6793 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6794 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6795 const APInt &SignBit = XorCST->getValue();
6796 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6797 ? ICI.getUnsignedPredicate()
6798 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006799 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006800 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006801 }
6802
6803 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006804 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006805 const APInt &NotSignBit = XorCST->getValue();
6806 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6807 ? ICI.getUnsignedPredicate()
6808 : ICI.getSignedPredicate();
6809 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006810 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006811 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006812 }
6813 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006814 }
6815 break;
6816 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6817 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6818 LHSI->getOperand(0)->hasOneUse()) {
6819 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6820
6821 // If the LHS is an AND of a truncating cast, we can widen the
6822 // and/compare to be the input width without changing the value
6823 // produced, eliminating a cast.
6824 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6825 // We can do this transformation if either the AND constant does not
6826 // have its sign bit set or if it is an equality comparison.
6827 // Extending a relational comparison when we're checking the sign
6828 // bit would not work.
6829 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006830 (ICI.isEquality() ||
6831 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006832 uint32_t BitWidth =
6833 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6834 APInt NewCST = AndCST->getValue();
6835 NewCST.zext(BitWidth);
6836 APInt NewCI = RHSV;
6837 NewCI.zext(BitWidth);
6838 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006839 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006840 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006841 InsertNewInstBefore(NewAnd, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006842 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006843 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006844 }
6845 }
6846
6847 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6848 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6849 // happens a LOT in code produced by the C front-end, for bitfield
6850 // access.
6851 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6852 if (Shift && !Shift->isShift())
6853 Shift = 0;
6854
6855 ConstantInt *ShAmt;
6856 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6857 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6858 const Type *AndTy = AndCST->getType(); // Type of the and.
6859
6860 // We can fold this as long as we can't shift unknown bits
6861 // into the mask. This can only happen with signed shift
6862 // rights, as they sign-extend.
6863 if (ShAmt) {
6864 bool CanFold = Shift->isLogicalShift();
6865 if (!CanFold) {
6866 // To test for the bad case of the signed shr, see if any
6867 // of the bits shifted in could be tested after the mask.
6868 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6869 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6870
6871 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6872 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6873 AndCST->getValue()) == 0)
6874 CanFold = true;
6875 }
6876
6877 if (CanFold) {
6878 Constant *NewCst;
6879 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006880 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006881 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006882 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006883
6884 // Check to see if we are shifting out any of the bits being
6885 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006886 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006887 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006888 // If we shifted bits out, the fold is not going to work out.
6889 // As a special case, check to see if this means that the
6890 // result is always true or false now.
6891 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006892 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006893 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006894 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006895 } else {
6896 ICI.setOperand(1, NewCst);
6897 Constant *NewAndCST;
6898 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006899 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006900 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006901 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006902 LHSI->setOperand(1, NewAndCST);
6903 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006904 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006905 AddUsesToWorkList(ICI);
6906 return &ICI;
6907 }
6908 }
6909 }
6910
6911 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6912 // preferable because it allows the C<<Y expression to be hoisted out
6913 // of a loop if Y is invariant and X is not.
6914 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006915 ICI.isEquality() && !Shift->isArithmeticShift() &&
6916 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006917 // Compute C << Y.
6918 Value *NS;
6919 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006920 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006921 Shift->getOperand(1), "tmp");
6922 } else {
6923 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006924 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006925 Shift->getOperand(1), "tmp");
6926 }
6927 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6928
6929 // Compute X & (C << Y).
6930 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006931 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006932 InsertNewInstBefore(NewAnd, ICI);
6933
6934 ICI.setOperand(0, NewAnd);
6935 return &ICI;
6936 }
6937 }
6938 break;
6939
Chris Lattnera0141b92007-07-15 20:42:37 +00006940 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6941 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6942 if (!ShAmt) break;
6943
6944 uint32_t TypeBits = RHSV.getBitWidth();
6945
6946 // Check that the shift amount is in range. If not, don't perform
6947 // undefined shifts. When the shift is visited it will be
6948 // simplified.
6949 if (ShAmt->uge(TypeBits))
6950 break;
6951
6952 if (ICI.isEquality()) {
6953 // If we are comparing against bits always shifted out, the
6954 // comparison cannot succeed.
6955 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006956 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006957 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006958 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6959 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006960 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006961 return ReplaceInstUsesWith(ICI, Cst);
6962 }
6963
6964 if (LHSI->hasOneUse()) {
6965 // Otherwise strength reduce the shift into an and.
6966 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6967 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006968 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006969 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006970
Chris Lattnera0141b92007-07-15 20:42:37 +00006971 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006972 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006973 Mask, LHSI->getName()+".mask");
6974 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006975 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006976 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977 }
6978 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006979
6980 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6981 bool TrueIfSigned = false;
6982 if (LHSI->hasOneUse() &&
6983 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6984 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006985 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006986 (TypeBits-ShAmt->getZExtValue()-1));
6987 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006988 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006989 Mask, LHSI->getName()+".mask");
6990 Value *And = InsertNewInstBefore(AndI, ICI);
6991
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006992 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006993 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006994 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006995 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006996 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006997
6998 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006999 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007000 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007001 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007002 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007003
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007004 // Check that the shift amount is in range. If not, don't perform
7005 // undefined shifts. When the shift is visited it will be
7006 // simplified.
7007 uint32_t TypeBits = RHSV.getBitWidth();
7008 if (ShAmt->uge(TypeBits))
7009 break;
7010
7011 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007012
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007013 // If we are comparing against bits always shifted out, the
7014 // comparison cannot succeed.
7015 APInt Comp = RHSV << ShAmtVal;
7016 if (LHSI->getOpcode() == Instruction::LShr)
7017 Comp = Comp.lshr(ShAmtVal);
7018 else
7019 Comp = Comp.ashr(ShAmtVal);
7020
7021 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7022 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007023 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007024 return ReplaceInstUsesWith(ICI, Cst);
7025 }
7026
7027 // Otherwise, check to see if the bits shifted out are known to be zero.
7028 // If so, we can compare against the unshifted value:
7029 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007030 if (LHSI->hasOneUse() &&
7031 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007032 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007033 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007034 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007035 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007036
Evan Chengf30752c2008-04-23 00:38:06 +00007037 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007038 // Otherwise strength reduce the shift into an and.
7039 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007040 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007041
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007042 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007043 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007044 Mask, LHSI->getName()+".mask");
7045 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007046 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007047 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007048 }
7049 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007050 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007051
7052 case Instruction::SDiv:
7053 case Instruction::UDiv:
7054 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7055 // Fold this div into the comparison, producing a range check.
7056 // Determine, based on the divide type, what the range is being
7057 // checked. If there is an overflow on the low or high side, remember
7058 // it, otherwise compute the range [low, hi) bounding the new value.
7059 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007060 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7061 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7062 DivRHS))
7063 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007064 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007065
7066 case Instruction::Add:
7067 // Fold: icmp pred (add, X, C1), C2
7068
7069 if (!ICI.isEquality()) {
7070 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7071 if (!LHSC) break;
7072 const APInt &LHSV = LHSC->getValue();
7073
7074 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7075 .subtract(LHSV);
7076
7077 if (ICI.isSignedPredicate()) {
7078 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007079 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007080 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007081 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007082 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007083 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007084 }
7085 } else {
7086 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007087 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007088 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007089 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007090 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007091 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007092 }
7093 }
7094 }
7095 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 }
7097
7098 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7099 if (ICI.isEquality()) {
7100 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7101
7102 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7103 // the second operand is a constant, simplify a bit.
7104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7105 switch (BO->getOpcode()) {
7106 case Instruction::SRem:
7107 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7108 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7109 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7110 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7111 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007112 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007113 BO->getName());
7114 InsertNewInstBefore(NewRem, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007115 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007116 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007117 }
7118 }
7119 break;
7120 case Instruction::Add:
7121 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7122 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7123 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007124 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007125 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126 } else if (RHSV == 0) {
7127 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7128 // efficiently invertible, or if the add has just this one use.
7129 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7130
Dan Gohman186a6362009-08-12 16:04:34 +00007131 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007132 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007133 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007134 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007135 else if (BO->hasOneUse()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00007136 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007137 InsertNewInstBefore(Neg, ICI);
7138 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007139 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007140 }
7141 }
7142 break;
7143 case Instruction::Xor:
7144 // For the xor case, we can xor two constants together, eliminating
7145 // the explicit xor.
7146 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007147 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007148 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149
7150 // FALLTHROUGH
7151 case Instruction::Sub:
7152 // Replace (([sub|xor] A, B) != 0) with (A != B)
7153 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007154 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155 BO->getOperand(1));
7156 break;
7157
7158 case Instruction::Or:
7159 // If bits are being or'd in that are not present in the constant we
7160 // are comparing against, then the comparison could never succeed!
7161 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007162 Constant *NotCI = ConstantExpr::getNot(RHS);
7163 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007164 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007165 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007166 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 }
7168 break;
7169
7170 case Instruction::And:
7171 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7172 // If bits are being compared against that are and'd out, then the
7173 // comparison can never succeed!
7174 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007175 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007176 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007177 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007178
7179 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7180 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007181 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007183 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007184
7185 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007186 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007187 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007188 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007189 ICmpInst::Predicate pred = isICMP_NE ?
7190 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007191 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007192 }
7193
7194 // ((X & ~7) == 0) --> X < 8
7195 if (RHSV == 0 && isHighOnes(BOC)) {
7196 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007197 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007198 ICmpInst::Predicate pred = isICMP_NE ?
7199 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007200 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007201 }
7202 }
7203 default: break;
7204 }
7205 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7206 // Handle icmp {eq|ne} <intrinsic>, intcst.
7207 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007208 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007209 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007210 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007211 return &ICI;
7212 }
7213 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007214 }
7215 return 0;
7216}
7217
7218/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7219/// We only handle extending casts so far.
7220///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7222 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007223 Value *LHSCIOp = LHSCI->getOperand(0);
7224 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007226 Value *RHSCIOp;
7227
Chris Lattner8c756c12007-05-05 22:41:33 +00007228 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7229 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007230 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7231 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007232 cast<IntegerType>(DestTy)->getBitWidth()) {
7233 Value *RHSOp = 0;
7234 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007235 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007236 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7237 RHSOp = RHSC->getOperand(0);
7238 // If the pointer types don't match, insert a bitcast.
7239 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007240 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007241 }
7242
7243 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007244 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007245 }
7246
7247 // The code below only handles extension cast instructions, so far.
7248 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249 if (LHSCI->getOpcode() != Instruction::ZExt &&
7250 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007251 return 0;
7252
Reid Spencere4d87aa2006-12-23 06:05:41 +00007253 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7254 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007255
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007257 // Not an extension from the same type?
7258 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 if (RHSCIOp->getType() != LHSCIOp->getType())
7260 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007261
Nick Lewycky4189a532008-01-28 03:48:02 +00007262 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007263 // and the other is a zext), then we can't handle this.
7264 if (CI->getOpcode() != LHSCI->getOpcode())
7265 return 0;
7266
Nick Lewycky4189a532008-01-28 03:48:02 +00007267 // Deal with equality cases early.
7268 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007269 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007270
7271 // A signed comparison of sign extended values simplifies into a
7272 // signed comparison.
7273 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007274 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007275
7276 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007277 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007278 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007279
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 // If we aren't dealing with a constant on the RHS, exit early
7281 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7282 if (!CI)
7283 return 0;
7284
7285 // Compute the constant that would happen if we truncated to SrcTy then
7286 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007287 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7288 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007289 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007290
7291 // If the re-extended constant didn't change...
7292 if (Res2 == CI) {
7293 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7294 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007295 // %A = sext i16 %X to i32
7296 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007298 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007299 // because %A may have negative value.
7300 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007301 // However, we allow this when the compare is EQ/NE, because they are
7302 // signless.
7303 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007304 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007305 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007306 }
7307
7308 // The re-extended constant changed so the constant cannot be represented
7309 // in the shorter type. Consequently, we cannot emit a simple comparison.
7310
7311 // First, handle some easy cases. We know the result cannot be equal at this
7312 // point so handle the ICI.isEquality() cases
7313 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007314 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007315 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007316 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007317
7318 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7319 // should have been folded away previously and not enter in here.
7320 Value *Result;
7321 if (isSignedCmp) {
7322 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007323 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007324 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007325 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007326 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007327 } else {
7328 // We're performing an unsigned comparison.
7329 if (isSignedExt) {
7330 // We're performing an unsigned comp with a sign extended value.
7331 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007332 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007333 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
Owen Anderson333c4002009-07-09 23:48:35 +00007334 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007335 } else {
7336 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007337 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007338 }
7339 }
7340
7341 // Finally, return the value computed.
7342 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007343 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007344 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007345
7346 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7347 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7348 "ICmp should be folded!");
7349 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007350 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007351 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007352}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007353
Reid Spencer832254e2007-02-02 02:16:23 +00007354Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7355 return commonShiftTransforms(I);
7356}
7357
7358Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7359 return commonShiftTransforms(I);
7360}
7361
7362Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007363 if (Instruction *R = commonShiftTransforms(I))
7364 return R;
7365
7366 Value *Op0 = I.getOperand(0);
7367
7368 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7369 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7370 if (CSI->isAllOnesValue())
7371 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007372
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007373 // See if we can turn a signed shr into an unsigned shr.
7374 if (MaskedValueIsZero(Op0,
7375 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7376 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7377
7378 // Arithmetic shifting an all-sign-bit value is a no-op.
7379 unsigned NumSignBits = ComputeNumSignBits(Op0);
7380 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7381 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007382
Chris Lattner348f6652007-12-06 01:59:46 +00007383 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007384}
7385
7386Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7387 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007388 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007389
7390 // shl X, 0 == X and shr X, 0 == X
7391 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007392 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7393 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007394 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007395
Reid Spencere4d87aa2006-12-23 06:05:41 +00007396 if (isa<UndefValue>(Op0)) {
7397 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007398 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007399 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007400 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007401 }
7402 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007403 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7404 return ReplaceInstUsesWith(I, Op0);
7405 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007406 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007407 }
7408
Dan Gohman9004c8a2009-05-21 02:28:33 +00007409 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007410 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007411 return &I;
7412
Chris Lattner2eefe512004-04-09 19:05:30 +00007413 // Try to fold constant and into select arguments.
7414 if (isa<Constant>(Op0))
7415 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007416 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007417 return R;
7418
Reid Spencerb83eb642006-10-20 07:07:24 +00007419 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007420 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7421 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007422 return 0;
7423}
7424
Reid Spencerb83eb642006-10-20 07:07:24 +00007425Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007426 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007427 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007428
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007429 // See if we can simplify any instructions used by the instruction whose sole
7430 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007431 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007432
Dan Gohmana119de82009-06-14 23:30:43 +00007433 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7434 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007435 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007436 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007437 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007438 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007439 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007440 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007441 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007442 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007443 }
7444
7445 // ((X*C1) << C2) == (X * (C1 << C2))
7446 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7447 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7448 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007449 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007450 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007451
7452 // Try to fold constant and into select arguments.
7453 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7454 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7455 return R;
7456 if (isa<PHINode>(Op0))
7457 if (Instruction *NV = FoldOpIntoPhi(I))
7458 return NV;
7459
Chris Lattner8999dd32007-12-22 09:07:47 +00007460 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7461 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7462 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7463 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7464 // place. Don't try to do this transformation in this case. Also, we
7465 // require that the input operand is a shift-by-constant so that we have
7466 // confidence that the shifts will get folded together. We could do this
7467 // xform in more cases, but it is unlikely to be profitable.
7468 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7469 isa<ConstantInt>(TrOp->getOperand(1))) {
7470 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007471 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007472 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007473 I.getName());
7474 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7475
7476 // For logical shifts, the truncation has the effect of making the high
7477 // part of the register be zeros. Emulate this by inserting an AND to
7478 // clear the top bits as needed. This 'and' will usually be zapped by
7479 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007480 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7481 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007482 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7483
7484 // The mask we constructed says what the trunc would do if occurring
7485 // between the shifts. We want to know the effect *after* the second
7486 // shift. We know that it is a logical shift by a constant, so adjust the
7487 // mask as appropriate.
7488 if (I.getOpcode() == Instruction::Shl)
7489 MaskV <<= Op1->getZExtValue();
7490 else {
7491 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7492 MaskV = MaskV.lshr(Op1->getZExtValue());
7493 }
7494
Owen Andersond672ecb2009-07-03 00:17:18 +00007495 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007496 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007497 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007498 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7499
7500 // Return the value truncated to the interesting size.
7501 return new TruncInst(And, I.getType());
7502 }
7503 }
7504
Chris Lattner4d5542c2006-01-06 07:12:35 +00007505 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007506 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7507 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7508 Value *V1, *V2;
7509 ConstantInt *CC;
7510 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007511 default: break;
7512 case Instruction::Add:
7513 case Instruction::And:
7514 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007515 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007516 // These operators commute.
7517 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007518 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007519 match(Op0BO->getOperand(1), 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(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007522 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007523 Op0BO->getName());
7524 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(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007527 Op0BO->getOperand(1)->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 Lattner150f12a2005-09-18 06:30:59 +00007534 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007535 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007536 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007537 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007538 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007539 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007540 cast<BinaryOperator>(Op0BOOp1)->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(0), 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(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007552 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007553 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007554
Reid Spencera07cb7d2007-02-02 14:41:37 +00007555 // FALL THROUGH.
7556 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007557 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007558 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007559 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007560 m_Specific(Op1)))) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007561 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007562 Op0BO->getOperand(1), Op1,
7563 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007564 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007565 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007566 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007567 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007568 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007569 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007570 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007571 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007572 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007573
Chris Lattner13d4ab42006-05-31 21:14:00 +00007574 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007575 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7576 match(Op0BO->getOperand(0),
7577 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007578 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007579 cast<BinaryOperator>(Op0BO->getOperand(0))
7580 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007581 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007582 Op0BO->getOperand(1), Op1,
7583 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007584 InsertNewInstBefore(YS, I); // (Y << C)
7585 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007586 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007587 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007588 V1->getName()+".mask");
7589 InsertNewInstBefore(XM, I); // X & (CC << C)
7590
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007591 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007592 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007593
Chris Lattner11021cb2005-09-18 05:12:10 +00007594 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007595 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007596 }
7597
7598
7599 // If the operand is an bitwise operator with a constant RHS, and the
7600 // shift is the only use, we can pull it out of the shift.
7601 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7602 bool isValid = true; // Valid only for And, Or, Xor
7603 bool highBitSet = false; // Transform if high bit of constant set?
7604
7605 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007606 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007607 case Instruction::Add:
7608 isValid = isLeftShift;
7609 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007610 case Instruction::Or:
7611 case Instruction::Xor:
7612 highBitSet = false;
7613 break;
7614 case Instruction::And:
7615 highBitSet = true;
7616 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007617 }
7618
7619 // If this is a signed shift right, and the high bit is modified
7620 // by the logical operation, do not perform the transformation.
7621 // The highBitSet boolean indicates the value of the high bit of
7622 // the constant which would cause it to be modified for this
7623 // operation.
7624 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007625 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007626 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007627
7628 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007629 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007630
7631 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007632 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007633 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007634 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007635
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007636 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007637 NewRHS);
7638 }
7639 }
7640 }
7641 }
7642
Chris Lattnerad0124c2006-01-06 07:52:12 +00007643 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007644 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7645 if (ShiftOp && !ShiftOp->isShift())
7646 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007647
Reid Spencerb83eb642006-10-20 07:07:24 +00007648 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007649 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007650 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7651 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007652 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7653 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7654 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007655
Zhou Sheng4351c642007-04-02 08:20:41 +00007656 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007657
7658 const IntegerType *Ty = cast<IntegerType>(I.getType());
7659
7660 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007661 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007662 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7663 // saturates.
7664 if (AmtSum >= TypeBits) {
7665 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007666 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007667 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7668 }
7669
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007670 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007671 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007672 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7673 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007674 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007675 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007676
Chris Lattnerb87056f2007-02-05 00:57:54 +00007677 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007678 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007679 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7680 I.getOpcode() == Instruction::LShr) {
7681 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007682 if (AmtSum >= TypeBits)
7683 AmtSum = TypeBits-1;
7684
Chris Lattnerb87056f2007-02-05 00:57:54 +00007685 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007686 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007687 InsertNewInstBefore(Shift, I);
7688
Zhou Shenge9e03f62007-03-28 15:02:20 +00007689 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007690 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007691 }
7692
Chris Lattnerb87056f2007-02-05 00:57:54 +00007693 // Okay, if we get here, one shift must be left, and the other shift must be
7694 // right. See if the amounts are equal.
7695 if (ShiftAmt1 == ShiftAmt2) {
7696 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7697 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007698 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007699 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700 }
7701 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7702 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007703 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007704 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007705 }
7706 // We can simplify ((X << C) >>s C) into a trunc + sext.
7707 // NOTE: we could do this for any C, but that would make 'unusual' integer
7708 // types. For now, just stick to ones well-supported by the code
7709 // generators.
7710 const Type *SExtType = 0;
7711 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007712 case 1 :
7713 case 8 :
7714 case 16 :
7715 case 32 :
7716 case 64 :
7717 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007718 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007719 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720 default: break;
7721 }
7722 if (SExtType) {
7723 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7724 InsertNewInstBefore(NewTrunc, I);
7725 return new SExtInst(NewTrunc, Ty);
7726 }
7727 // Otherwise, we can't handle it yet.
7728 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007729 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007730
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007731 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007732 if (I.getOpcode() == Instruction::Shl) {
7733 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7734 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007735 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007736 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007737 InsertNewInstBefore(Shift, I);
7738
Reid Spencer55702aa2007-03-25 21:11:44 +00007739 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007740 return BinaryOperator::CreateAnd(Shift,
7741 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007742 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007743
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007744 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007745 if (I.getOpcode() == Instruction::LShr) {
7746 assert(ShiftOp->getOpcode() == Instruction::Shl);
7747 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007748 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007749 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007750
Reid Spencerd5e30f02007-03-26 17:18:58 +00007751 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007752 return BinaryOperator::CreateAnd(Shift,
7753 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007754 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007755
7756 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7757 } else {
7758 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007759 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007760
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007761 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007762 if (I.getOpcode() == Instruction::Shl) {
7763 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7764 ShiftOp->getOpcode() == Instruction::AShr);
7765 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007766 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007767 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007768 InsertNewInstBefore(Shift, I);
7769
Reid Spencer55702aa2007-03-25 21:11:44 +00007770 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007771 return BinaryOperator::CreateAnd(Shift,
7772 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007773 }
7774
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007775 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007776 if (I.getOpcode() == Instruction::LShr) {
7777 assert(ShiftOp->getOpcode() == Instruction::Shl);
7778 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007779 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007780 InsertNewInstBefore(Shift, I);
7781
Reid Spencer68d27cf2007-03-26 23:45:51 +00007782 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007783 return BinaryOperator::CreateAnd(Shift,
7784 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007785 }
7786
7787 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007788 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007789 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007790 return 0;
7791}
7792
Chris Lattnera1be5662002-05-02 17:06:02 +00007793
Chris Lattnercfd65102005-10-29 04:36:15 +00007794/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7795/// expression. If so, decompose it, returning some value X, such that Val is
7796/// X*Scale+Offset.
7797///
7798static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007799 int &Offset, LLVMContext *Context) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007800 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007801 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007802 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007803 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007804 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007805 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7807 if (I->getOpcode() == Instruction::Shl) {
7808 // This is a value scaled by '1 << the shift amt'.
7809 Scale = 1U << RHS->getZExtValue();
7810 Offset = 0;
7811 return I->getOperand(0);
7812 } else if (I->getOpcode() == Instruction::Mul) {
7813 // This value is scaled by 'RHS'.
7814 Scale = RHS->getZExtValue();
7815 Offset = 0;
7816 return I->getOperand(0);
7817 } else if (I->getOpcode() == Instruction::Add) {
7818 // We have X+C. Check to see if we really have (X*C2)+C1,
7819 // where C1 is divisible by C2.
7820 unsigned SubScale;
7821 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007822 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7823 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007824 Offset += RHS->getZExtValue();
7825 Scale = SubScale;
7826 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007827 }
7828 }
7829 }
7830
7831 // Otherwise, we can't look past this.
7832 Scale = 1;
7833 Offset = 0;
7834 return Val;
7835}
7836
7837
Chris Lattnerb3f83972005-10-24 06:03:58 +00007838/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7839/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007840Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007841 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007842 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007843
Chris Lattnerb53c2382005-10-24 06:22:12 +00007844 // Remove any uses of AI that are dead.
7845 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007846
Chris Lattnerb53c2382005-10-24 06:22:12 +00007847 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7848 Instruction *User = cast<Instruction>(*UI++);
7849 if (isInstructionTriviallyDead(User)) {
7850 while (UI != E && *UI == User)
7851 ++UI; // If this instruction uses AI more than once, don't break UI.
7852
Chris Lattnerb53c2382005-10-24 06:22:12 +00007853 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007854 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007855 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007856 }
7857 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007858
7859 // This requires TargetData to get the alloca alignment and size information.
7860 if (!TD) return 0;
7861
Chris Lattnerb3f83972005-10-24 06:03:58 +00007862 // Get the type really allocated and the type casted to.
7863 const Type *AllocElTy = AI.getAllocatedType();
7864 const Type *CastElTy = PTy->getElementType();
7865 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007866
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007867 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7868 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007869 if (CastElTyAlign < AllocElTyAlign) return 0;
7870
Chris Lattner39387a52005-10-24 06:35:18 +00007871 // If the allocation has multiple uses, only promote it if we are strictly
7872 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007873 // same, we open the door to infinite loops of various kinds. (A reference
7874 // from a dbg.declare doesn't count as a use for this purpose.)
7875 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7876 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007877
Duncan Sands777d2302009-05-09 07:06:46 +00007878 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7879 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007880 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007881
Chris Lattner455fcc82005-10-29 03:19:53 +00007882 // See if we can satisfy the modulus by pulling a scale out of the array
7883 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007884 unsigned ArraySizeScale;
7885 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007886 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007887 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7888 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007889
Chris Lattner455fcc82005-10-29 03:19:53 +00007890 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7891 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007892 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7893 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007894
Chris Lattner455fcc82005-10-29 03:19:53 +00007895 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7896 Value *Amt = 0;
7897 if (Scale == 1) {
7898 Amt = NumElements;
7899 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007900 // If the allocation size is constant, form a constant mul expression
Owen Anderson1d0be152009-08-13 21:58:54 +00007901 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007902 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007903 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007904 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007905 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007906 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007907 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007908 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007909 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007910 }
7911
Jeff Cohen86796be2007-04-04 16:58:57 +00007912 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007913 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007914 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007915 Amt = InsertNewInstBefore(Tmp, AI);
7916 }
7917
Chris Lattnerb3f83972005-10-24 06:03:58 +00007918 AllocationInst *New;
7919 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007920 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007921 else
Owen Anderson50dead02009-07-15 23:53:25 +00007922 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007923 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007924 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007925
Dale Johannesena0a66372009-03-05 00:39:02 +00007926 // If the allocation has one real use plus a dbg.declare, just remove the
7927 // declare.
7928 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7929 EraseInstFromFunction(*DI);
7930 }
7931 // If the allocation has multiple real uses, insert a cast and change all
7932 // things that used it to use the new cast. This will also hack on CI, but it
7933 // will die soon.
7934 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007935 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007936 // New is the allocation instruction, pointer typed. AI is the original
7937 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7938 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007939 InsertNewInstBefore(NewCast, AI);
7940 AI.replaceAllUsesWith(NewCast);
7941 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007942 return ReplaceInstUsesWith(CI, New);
7943}
7944
Chris Lattner70074e02006-05-13 02:06:03 +00007945/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007946/// and return it as type Ty without inserting any new casts and without
7947/// changing the computed value. This is used by code that tries to decide
7948/// whether promoting or shrinking integer operations to wider or smaller types
7949/// will allow us to eliminate a truncate or extend.
7950///
7951/// This is a truncation operation if Ty is smaller than V->getType(), or an
7952/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007953///
7954/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7955/// should return true if trunc(V) can be computed by computing V in the smaller
7956/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7957/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7958/// efficiently truncated.
7959///
7960/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7961/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7962/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007963bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007964 unsigned CastOpc,
7965 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007966 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007967 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007968 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007969
7970 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007971 if (!I) return false;
7972
Dan Gohman6de29f82009-06-15 22:12:54 +00007973 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007974
Chris Lattner951626b2007-08-02 06:11:14 +00007975 // If this is an extension or truncate, we can often eliminate it.
7976 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7977 // If this is a cast from the destination type, we can trivially eliminate
7978 // it, and this will remove a cast overall.
7979 if (I->getOperand(0)->getType() == Ty) {
7980 // If the first operand is itself a cast, and is eliminable, do not count
7981 // this as an eliminable cast. We would prefer to eliminate those two
7982 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007983 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007984 ++NumCastsRemoved;
7985 return true;
7986 }
7987 }
7988
7989 // We can't extend or shrink something that has multiple uses: doing so would
7990 // require duplicating the instruction in general, which isn't profitable.
7991 if (!I->hasOneUse()) return false;
7992
Evan Chengf35fd542009-01-15 17:01:23 +00007993 unsigned Opc = I->getOpcode();
7994 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007995 case Instruction::Add:
7996 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007997 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007998 case Instruction::And:
7999 case Instruction::Or:
8000 case Instruction::Xor:
8001 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008002 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008003 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008004 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008005 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008006
Eli Friedman070a9812009-07-13 22:46:01 +00008007 case Instruction::UDiv:
8008 case Instruction::URem: {
8009 // UDiv and URem can be truncated if all the truncated bits are zero.
8010 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8011 uint32_t BitWidth = Ty->getScalarSizeInBits();
8012 if (BitWidth < OrigBitWidth) {
8013 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8014 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8015 MaskedValueIsZero(I->getOperand(1), Mask)) {
8016 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8017 NumCastsRemoved) &&
8018 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8019 NumCastsRemoved);
8020 }
8021 }
8022 break;
8023 }
Chris Lattner46b96052006-11-29 07:18:39 +00008024 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008025 // If we are truncating the result of this SHL, and if it's a shift of a
8026 // constant amount, we can always perform a SHL in a smaller type.
8027 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008028 uint32_t BitWidth = Ty->getScalarSizeInBits();
8029 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008030 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008031 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008032 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008033 }
8034 break;
8035 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008036 // If this is a truncate of a logical shr, we can truncate it to a smaller
8037 // lshr iff we know that the bits we would otherwise be shifting in are
8038 // already zeros.
8039 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008040 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8041 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008042 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008043 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008044 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8045 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008046 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008047 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008048 }
8049 }
Chris Lattner46b96052006-11-29 07:18:39 +00008050 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008051 case Instruction::ZExt:
8052 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008053 case Instruction::Trunc:
8054 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008055 // can safely replace it. Note that replacing it does not reduce the number
8056 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008057 if (Opc == CastOpc)
8058 return true;
8059
8060 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008061 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008062 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008063 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008064 case Instruction::Select: {
8065 SelectInst *SI = cast<SelectInst>(I);
8066 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008067 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008068 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008069 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008070 }
Chris Lattner8114b712008-06-18 04:00:49 +00008071 case Instruction::PHI: {
8072 // We can change a phi if we can change all operands.
8073 PHINode *PN = cast<PHINode>(I);
8074 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8075 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008076 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008077 return false;
8078 return true;
8079 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008080 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008081 // TODO: Can handle more cases here.
8082 break;
8083 }
8084
8085 return false;
8086}
8087
8088/// EvaluateInDifferentType - Given an expression that
8089/// CanEvaluateInDifferentType returns true for, actually insert the code to
8090/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008091Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008092 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008093 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008094 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008095 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008096
8097 // Otherwise, it must be an instruction.
8098 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008099 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008100 unsigned Opc = I->getOpcode();
8101 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008102 case Instruction::Add:
8103 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008104 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008105 case Instruction::And:
8106 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008107 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008108 case Instruction::AShr:
8109 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008110 case Instruction::Shl:
8111 case Instruction::UDiv:
8112 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008113 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008114 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008115 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008116 break;
8117 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008118 case Instruction::Trunc:
8119 case Instruction::ZExt:
8120 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008121 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008122 // just return the source. There's no need to insert it because it is not
8123 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008124 if (I->getOperand(0)->getType() == Ty)
8125 return I->getOperand(0);
8126
Chris Lattner8114b712008-06-18 04:00:49 +00008127 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008128 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008129 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008130 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008131 case Instruction::Select: {
8132 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8133 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8134 Res = SelectInst::Create(I->getOperand(0), True, False);
8135 break;
8136 }
Chris Lattner8114b712008-06-18 04:00:49 +00008137 case Instruction::PHI: {
8138 PHINode *OPN = cast<PHINode>(I);
8139 PHINode *NPN = PHINode::Create(Ty);
8140 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8141 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8142 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8143 }
8144 Res = NPN;
8145 break;
8146 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008147 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008148 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008149 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008150 break;
8151 }
8152
Chris Lattner8114b712008-06-18 04:00:49 +00008153 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008154 return InsertNewInstBefore(Res, *I);
8155}
8156
Reid Spencer3da59db2006-11-27 01:05:10 +00008157/// @brief Implement the transforms common to all CastInst visitors.
8158Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008159 Value *Src = CI.getOperand(0);
8160
Dan Gohman23d9d272007-05-11 21:10:54 +00008161 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008162 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008163 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008164 if (Instruction::CastOps opc =
8165 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8166 // The first cast (CSrc) is eliminable so we need to fix up or replace
8167 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008168 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008169 }
8170 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008171
Reid Spencer3da59db2006-11-27 01:05:10 +00008172 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008173 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8174 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8175 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008176
8177 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008178 if (isa<PHINode>(Src))
8179 if (Instruction *NV = FoldOpIntoPhi(CI))
8180 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008181
Reid Spencer3da59db2006-11-27 01:05:10 +00008182 return 0;
8183}
8184
Chris Lattner46cd5a12009-01-09 05:44:56 +00008185/// FindElementAtOffset - Given a type and a constant offset, determine whether
8186/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008187/// the specified offset. If so, fill them into NewIndices and return the
8188/// resultant element type, otherwise return null.
8189static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8190 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008191 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008192 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008193 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008194 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008195
8196 // Start with the index over the outer type. Note that the type size
8197 // might be zero (even if the offset isn't zero) if the indexed type
8198 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008199 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008200 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008201 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008202 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008203 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008204
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008205 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008206 if (Offset < 0) {
8207 --FirstIdx;
8208 Offset += TySize;
8209 assert(Offset >= 0);
8210 }
8211 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8212 }
8213
Owen Andersoneed707b2009-07-24 23:12:02 +00008214 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008215
8216 // Index into the types. If we fail, set OrigBase to null.
8217 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008218 // Indexing into tail padding between struct/array elements.
8219 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008220 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008221
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8223 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008224 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8225 "Offset must stay within the indexed type");
8226
Chris Lattner46cd5a12009-01-09 05:44:56 +00008227 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008228 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008229
8230 Offset -= SL->getElementOffset(Elt);
8231 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008232 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008233 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008234 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008235 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008236 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008237 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008238 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008239 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008240 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008241 }
8242 }
8243
Chris Lattner3914f722009-01-24 01:00:13 +00008244 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008245}
8246
Chris Lattnerd3e28342007-04-27 17:44:50 +00008247/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8248Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8249 Value *Src = CI.getOperand(0);
8250
Chris Lattnerd3e28342007-04-27 17:44:50 +00008251 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008252 // If casting the result of a getelementptr instruction with no offset, turn
8253 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008254 if (GEP->hasAllZeroIndices()) {
8255 // Changing the cast operand is usually not a good idea but it is safe
8256 // here because the pointer operand is being replaced with another
8257 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008258 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008259 CI.setOperand(0, GEP->getOperand(0));
8260 return &CI;
8261 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008262
8263 // If the GEP has a single use, and the base pointer is a bitcast, and the
8264 // GEP computes a constant offset, see if we can convert these three
8265 // instructions into fewer. This typically happens with unions and other
8266 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008267 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008268 if (GEP->hasAllConstantIndices()) {
8269 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008270 ConstantInt *OffsetV =
8271 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008272 int64_t Offset = OffsetV->getSExtValue();
8273
8274 // Get the base pointer input of the bitcast, and the type it points to.
8275 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8276 const Type *GEPIdxTy =
8277 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008278 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008279 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008280 // If we were able to index down into an element, create the GEP
8281 // and bitcast the result. This eliminates one bitcast, potentially
8282 // two.
8283 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8284 NewIndices.begin(),
8285 NewIndices.end(), "");
8286 InsertNewInstBefore(NGEP, CI);
8287 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008288 if (cast<GEPOperator>(GEP)->isInBounds())
8289 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008290
Chris Lattner46cd5a12009-01-09 05:44:56 +00008291 if (isa<BitCastInst>(CI))
8292 return new BitCastInst(NGEP, CI.getType());
8293 assert(isa<PtrToIntInst>(CI));
8294 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008295 }
8296 }
8297 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008298 }
8299
8300 return commonCastTransforms(CI);
8301}
8302
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008303/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8304/// type like i42. We don't want to introduce operations on random non-legal
8305/// integer types where they don't already exist in the code. In the future,
8306/// we should consider making this based off target-data, so that 32-bit targets
8307/// won't get i64 operations etc.
8308static bool isSafeIntegerType(const Type *Ty) {
8309 switch (Ty->getPrimitiveSizeInBits()) {
8310 case 8:
8311 case 16:
8312 case 32:
8313 case 64:
8314 return true;
8315 default:
8316 return false;
8317 }
8318}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008319
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008320/// commonIntCastTransforms - This function implements the common transforms
8321/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008322Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8323 if (Instruction *Result = commonCastTransforms(CI))
8324 return Result;
8325
8326 Value *Src = CI.getOperand(0);
8327 const Type *SrcTy = Src->getType();
8328 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008329 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8330 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008331
Reid Spencer3da59db2006-11-27 01:05:10 +00008332 // See if we can simplify any instructions used by the LHS whose sole
8333 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008334 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008335 return &CI;
8336
8337 // If the source isn't an instruction or has more than one use then we
8338 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008339 Instruction *SrcI = dyn_cast<Instruction>(Src);
8340 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008341 return 0;
8342
Chris Lattnerc739cd62007-03-03 05:27:34 +00008343 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008344 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008345 // Only do this if the dest type is a simple type, don't convert the
8346 // expression tree to something weird like i93 unless the source is also
8347 // strange.
8348 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008349 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8350 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008351 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008353 // eliminates the cast, so it is always a win. If this is a zero-extension,
8354 // we need to do an AND to maintain the clear top-part of the computation,
8355 // so we require that the input have eliminated at least one cast. If this
8356 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008357 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008358 bool DoXForm = false;
8359 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008360 switch (CI.getOpcode()) {
8361 default:
8362 // All the others use floating point so we shouldn't actually
8363 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008364 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008365 case Instruction::Trunc:
8366 DoXForm = true;
8367 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008368 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008369 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008370 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008371 // If it's unnecessary to issue an AND to clear the high bits, it's
8372 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008373 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8375 if (MaskedValueIsZero(TryRes, Mask))
8376 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008377
8378 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008379 if (TryI->use_empty())
8380 EraseInstFromFunction(*TryI);
8381 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008382 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008383 }
Evan Chengf35fd542009-01-15 17:01:23 +00008384 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008385 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008386 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008387 // If we do not have to emit the truncate + sext pair, then it's always
8388 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008389 //
8390 // It's not safe to eliminate the trunc + sext pair if one of the
8391 // eliminated cast is a truncate. e.g.
8392 // t2 = trunc i32 t1 to i16
8393 // t3 = sext i16 t2 to i32
8394 // !=
8395 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008396 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008397 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8398 if (NumSignBits > (DestBitSize - SrcBitSize))
8399 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008400
8401 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008402 if (TryI->use_empty())
8403 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008404 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008405 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008406 }
Evan Chengf35fd542009-01-15 17:01:23 +00008407 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008408
8409 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008410 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8411 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008412 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8413 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008414 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008415 // Just replace this cast with the result.
8416 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008417
Reid Spencer3da59db2006-11-27 01:05:10 +00008418 assert(Res->getType() == DestTy);
8419 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008420 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008421 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008422 // Just replace this cast with the result.
8423 return ReplaceInstUsesWith(CI, Res);
8424 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008425 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008426
8427 // If the high bits are already zero, just replace this cast with the
8428 // result.
8429 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8430 if (MaskedValueIsZero(Res, Mask))
8431 return ReplaceInstUsesWith(CI, Res);
8432
8433 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008434 Constant *C = ConstantInt::get(*Context,
8435 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008436 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008437 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008438 case Instruction::SExt: {
8439 // If the high bits are already filled with sign bit, just replace this
8440 // cast with the result.
8441 unsigned NumSignBits = ComputeNumSignBits(Res);
8442 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008443 return ReplaceInstUsesWith(CI, Res);
8444
Reid Spencer3da59db2006-11-27 01:05:10 +00008445 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008446 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008447 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8448 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008449 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008450 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008451 }
8452 }
8453
8454 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8455 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8456
8457 switch (SrcI->getOpcode()) {
8458 case Instruction::Add:
8459 case Instruction::Mul:
8460 case Instruction::And:
8461 case Instruction::Or:
8462 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008463 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008464 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8465 // Don't insert two casts unless at least one can be eliminated.
8466 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008467 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008468 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8469 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008470 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008471 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008472 }
8473 }
8474
8475 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8476 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8477 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008478 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008479 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008480 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008481 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008482 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008483 }
8484 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008485
Eli Friedman65445c52009-07-13 21:45:57 +00008486 case Instruction::Shl: {
8487 // Canonicalize trunc inside shl, if we can.
8488 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8489 if (CI && DestBitSize < SrcBitSize &&
8490 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8491 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8492 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008493 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008494 }
8495 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008496 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008497 }
8498 return 0;
8499}
8500
Chris Lattner8a9f5712007-04-11 06:57:46 +00008501Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008502 if (Instruction *Result = commonIntCastTransforms(CI))
8503 return Result;
8504
8505 Value *Src = CI.getOperand(0);
8506 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008507 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8508 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008509
8510 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008511 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008512 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008513 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008514 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008515 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008516 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008517
Chris Lattner4f9797d2009-03-24 18:15:30 +00008518 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8519 ConstantInt *ShAmtV = 0;
8520 Value *ShiftOp = 0;
8521 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008522 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008523 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8524
8525 // Get a mask for the bits shifting in.
8526 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8527 if (MaskedValueIsZero(ShiftOp, Mask)) {
8528 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008529 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008530
8531 // Okay, we can shrink this. Truncate the input, then return a new
8532 // shift.
8533 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008534 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008535 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008536 }
8537 }
8538
8539 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008540}
8541
Evan Chengb98a10e2008-03-24 00:21:34 +00008542/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8543/// in order to eliminate the icmp.
8544Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8545 bool DoXform) {
8546 // If we are just checking for a icmp eq of a single bit and zext'ing it
8547 // to an integer, then shift the bit to the appropriate place and then
8548 // cast to integer to avoid the comparison.
8549 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8550 const APInt &Op1CV = Op1C->getValue();
8551
8552 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8553 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8554 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8555 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8556 if (!DoXform) return ICI;
8557
8558 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008559 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008560 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008561 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008562 In->getName()+".lobit"),
8563 CI);
8564 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008565 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008566 false/*ZExt*/, "tmp", &CI);
8567
8568 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008569 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008570 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008571 In->getName()+".not"),
8572 CI);
8573 }
8574
8575 return ReplaceInstUsesWith(CI, In);
8576 }
8577
8578
8579
8580 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8581 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8582 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8583 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8584 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8585 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8586 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8587 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8588 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8589 // This only works for EQ and NE
8590 ICI->isEquality()) {
8591 // If Op1C some other power of two, convert:
8592 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8593 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8594 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8595 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8596
8597 APInt KnownZeroMask(~KnownZero);
8598 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8599 if (!DoXform) return ICI;
8600
8601 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8602 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8603 // (X&4) == 2 --> false
8604 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008605 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008606 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008607 return ReplaceInstUsesWith(CI, Res);
8608 }
8609
8610 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8611 Value *In = ICI->getOperand(0);
8612 if (ShiftAmt) {
8613 // Perform a logical shr by shiftamt.
8614 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008615 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008616 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008617 In->getName()+".lobit"), CI);
8618 }
8619
8620 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008621 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008622 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008623 InsertNewInstBefore(cast<Instruction>(In), CI);
8624 }
8625
8626 if (CI.getType() == In->getType())
8627 return ReplaceInstUsesWith(CI, In);
8628 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008629 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008630 }
8631 }
8632 }
8633
8634 return 0;
8635}
8636
Chris Lattner8a9f5712007-04-11 06:57:46 +00008637Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008638 // If one of the common conversion will work ..
8639 if (Instruction *Result = commonIntCastTransforms(CI))
8640 return Result;
8641
8642 Value *Src = CI.getOperand(0);
8643
Chris Lattnera84f47c2009-02-17 20:47:23 +00008644 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8645 // types and if the sizes are just right we can convert this into a logical
8646 // 'and' which will be much cheaper than the pair of casts.
8647 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8648 // Get the sizes of the types involved. We know that the intermediate type
8649 // will be smaller than A or C, but don't know the relation between A and C.
8650 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008651 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8652 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8653 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008654 // If we're actually extending zero bits, then if
8655 // SrcSize < DstSize: zext(a & mask)
8656 // SrcSize == DstSize: a & mask
8657 // SrcSize > DstSize: trunc(a) & mask
8658 if (SrcSize < DstSize) {
8659 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008660 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008661 Instruction *And =
8662 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8663 InsertNewInstBefore(And, CI);
8664 return new ZExtInst(And, CI.getType());
8665 } else if (SrcSize == DstSize) {
8666 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008667 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008668 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008669 } else if (SrcSize > DstSize) {
8670 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8671 InsertNewInstBefore(Trunc, CI);
8672 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008673 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008674 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008675 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008676 }
8677 }
8678
Evan Chengb98a10e2008-03-24 00:21:34 +00008679 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8680 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008681
Evan Chengb98a10e2008-03-24 00:21:34 +00008682 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8683 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8684 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8685 // of the (zext icmp) will be transformed.
8686 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8687 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8688 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8689 (transformZExtICmp(LHS, CI, false) ||
8690 transformZExtICmp(RHS, CI, false))) {
8691 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8692 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008693 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008694 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008695 }
8696
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008697 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008698 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8699 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8700 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8701 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008702 if (TI0->getType() == CI.getType())
8703 return
8704 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008705 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008706 }
8707
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008708 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8709 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8710 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8711 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8712 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8713 And->getOperand(1) == C)
8714 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8715 Value *TI0 = TI->getOperand(0);
8716 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008717 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008718 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8719 InsertNewInstBefore(NewAnd, *And);
8720 return BinaryOperator::CreateXor(NewAnd, ZC);
8721 }
8722 }
8723
Reid Spencer3da59db2006-11-27 01:05:10 +00008724 return 0;
8725}
8726
Chris Lattner8a9f5712007-04-11 06:57:46 +00008727Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008728 if (Instruction *I = commonIntCastTransforms(CI))
8729 return I;
8730
Chris Lattner8a9f5712007-04-11 06:57:46 +00008731 Value *Src = CI.getOperand(0);
8732
Dan Gohman1975d032008-10-30 20:40:10 +00008733 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008734 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008735 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008736 Constant::getAllOnesValue(CI.getType()),
8737 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008738
8739 // See if the value being truncated is already sign extended. If so, just
8740 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008741 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008742 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008743 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8744 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8745 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008746 unsigned NumSignBits = ComputeNumSignBits(Op);
8747
8748 if (OpBits == DestBits) {
8749 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8750 // bits, it is already ready.
8751 if (NumSignBits > DestBits-MidBits)
8752 return ReplaceInstUsesWith(CI, Op);
8753 } else if (OpBits < DestBits) {
8754 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8755 // bits, just sext from i32.
8756 if (NumSignBits > OpBits-MidBits)
8757 return new SExtInst(Op, CI.getType(), "tmp");
8758 } else {
8759 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8760 // bits, just truncate to i32.
8761 if (NumSignBits > OpBits-MidBits)
8762 return new TruncInst(Op, CI.getType(), "tmp");
8763 }
8764 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008765
8766 // If the input is a shl/ashr pair of a same constant, then this is a sign
8767 // extension from a smaller value. If we could trust arbitrary bitwidth
8768 // integers, we could turn this into a truncate to the smaller bit and then
8769 // use a sext for the whole extension. Since we don't, look deeper and check
8770 // for a truncate. If the source and dest are the same type, eliminate the
8771 // trunc and extend and just do shifts. For example, turn:
8772 // %a = trunc i32 %i to i8
8773 // %b = shl i8 %a, 6
8774 // %c = ashr i8 %b, 6
8775 // %d = sext i8 %c to i32
8776 // into:
8777 // %a = shl i32 %i, 30
8778 // %d = ashr i32 %a, 30
8779 Value *A = 0;
8780 ConstantInt *BA = 0, *CA = 0;
8781 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008782 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008783 BA == CA && isa<TruncInst>(A)) {
8784 Value *I = cast<TruncInst>(A)->getOperand(0);
8785 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008786 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8787 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008788 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008789 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008790 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8791 CI.getName()), CI);
8792 return BinaryOperator::CreateAShr(I, ShAmtV);
8793 }
8794 }
8795
Chris Lattnerba417832007-04-11 06:12:58 +00008796 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008797}
8798
Chris Lattnerb7530652008-01-27 05:29:54 +00008799/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8800/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008801static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008802 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008803 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008805 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8806 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008807 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008808 return 0;
8809}
8810
8811/// LookThroughFPExtensions - If this is an fp extension instruction, look
8812/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008813static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008814 if (Instruction *I = dyn_cast<Instruction>(V))
8815 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008816 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008817
8818 // If this value is a constant, return the constant in the smallest FP type
8819 // that can accurately represent it. This allows us to turn
8820 // (float)((double)X+2.0) into x+2.0f.
8821 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008822 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008823 return V; // No constant folding of this.
8824 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008825 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008826 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008827 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008828 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008829 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008830 return V;
8831 // Don't try to shrink to various long double types.
8832 }
8833
8834 return V;
8835}
8836
8837Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8838 if (Instruction *I = commonCastTransforms(CI))
8839 return I;
8840
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008841 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008842 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008843 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008844 // many builtins (sqrt, etc).
8845 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8846 if (OpI && OpI->hasOneUse()) {
8847 switch (OpI->getOpcode()) {
8848 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008849 case Instruction::FAdd:
8850 case Instruction::FSub:
8851 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008852 case Instruction::FDiv:
8853 case Instruction::FRem:
8854 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008855 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8856 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008857 if (LHSTrunc->getType() != SrcTy &&
8858 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008859 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008860 // If the source types were both smaller than the destination type of
8861 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008862 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8863 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008864 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8865 CI.getType(), CI);
8866 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8867 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008868 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008869 }
8870 }
8871 break;
8872 }
8873 }
8874 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008875}
8876
8877Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8878 return commonCastTransforms(CI);
8879}
8880
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008881Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008882 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8883 if (OpI == 0)
8884 return commonCastTransforms(FI);
8885
8886 // fptoui(uitofp(X)) --> X
8887 // fptoui(sitofp(X)) --> X
8888 // This is safe if the intermediate type has enough bits in its mantissa to
8889 // accurately represent all values of X. For example, do not do this with
8890 // i64->float->i64. This is also safe for sitofp case, because any negative
8891 // 'X' value would cause an undefined result for the fptoui.
8892 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8893 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008894 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008895 OpI->getType()->getFPMantissaWidth())
8896 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008897
8898 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008899}
8900
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008901Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008902 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8903 if (OpI == 0)
8904 return commonCastTransforms(FI);
8905
8906 // fptosi(sitofp(X)) --> X
8907 // fptosi(uitofp(X)) --> X
8908 // This is safe if the intermediate type has enough bits in its mantissa to
8909 // accurately represent all values of X. For example, do not do this with
8910 // i64->float->i64. This is also safe for sitofp case, because any negative
8911 // 'X' value would cause an undefined result for the fptoui.
8912 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8913 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008914 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008915 OpI->getType()->getFPMantissaWidth())
8916 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008917
8918 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008919}
8920
8921Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8922 return commonCastTransforms(CI);
8923}
8924
8925Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8926 return commonCastTransforms(CI);
8927}
8928
Chris Lattnera0e69692009-03-24 18:35:40 +00008929Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8930 // If the destination integer type is smaller than the intptr_t type for
8931 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8932 // trunc to be exposed to other transforms. Don't do this for extending
8933 // ptrtoint's, because we don't know if the target sign or zero extends its
8934 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008935 if (TD &&
8936 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008937 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008938 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008939 "tmp"), CI);
8940 return new TruncInst(P, CI.getType());
8941 }
8942
Chris Lattnerd3e28342007-04-27 17:44:50 +00008943 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008944}
8945
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008946Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008947 // If the source integer type is larger than the intptr_t type for
8948 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8949 // allows the trunc to be exposed to other transforms. Don't do this for
8950 // extending inttoptr's, because we don't know if the target sign or zero
8951 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008952 if (TD &&
8953 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008954 TD->getPointerSizeInBits()) {
8955 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008956 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008957 "tmp"), CI);
8958 return new IntToPtrInst(P, CI.getType());
8959 }
8960
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008961 if (Instruction *I = commonCastTransforms(CI))
8962 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008963
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008964 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008965}
8966
Chris Lattnerd3e28342007-04-27 17:44:50 +00008967Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008968 // If the operands are integer typed then apply the integer transforms,
8969 // otherwise just apply the common ones.
8970 Value *Src = CI.getOperand(0);
8971 const Type *SrcTy = Src->getType();
8972 const Type *DestTy = CI.getType();
8973
Eli Friedman7e25d452009-07-13 20:53:00 +00008974 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008975 if (Instruction *I = commonPointerCastTransforms(CI))
8976 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008977 } else {
8978 if (Instruction *Result = commonCastTransforms(CI))
8979 return Result;
8980 }
8981
8982
8983 // Get rid of casts from one type to the same type. These are useless and can
8984 // be replaced by the operand.
8985 if (DestTy == Src->getType())
8986 return ReplaceInstUsesWith(CI, Src);
8987
Reid Spencer3da59db2006-11-27 01:05:10 +00008988 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008989 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8990 const Type *DstElTy = DstPTy->getElementType();
8991 const Type *SrcElTy = SrcPTy->getElementType();
8992
Nate Begeman83ad90a2008-03-31 00:22:16 +00008993 // If the address spaces don't match, don't eliminate the bitcast, which is
8994 // required for changing types.
8995 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8996 return 0;
8997
Chris Lattnerd3e28342007-04-27 17:44:50 +00008998 // If we are casting a malloc or alloca to a pointer to a type of the same
8999 // size, rewrite the allocation instruction to allocate the "right" type.
9000 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9001 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9002 return V;
9003
Chris Lattnerd717c182007-05-05 22:32:24 +00009004 // If the source and destination are pointers, and this cast is equivalent
9005 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009006 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009007 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009008 unsigned NumZeros = 0;
9009 while (SrcElTy != DstElTy &&
9010 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9011 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9012 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9013 ++NumZeros;
9014 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009015
Chris Lattnerd3e28342007-04-27 17:44:50 +00009016 // If we found a path from the src to dest, create the getelementptr now.
9017 if (SrcElTy == DstElTy) {
9018 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00009019 Instruction *GEP = GetElementPtrInst::Create(Src,
9020 Idxs.begin(), Idxs.end(), "",
9021 ((Instruction*) NULL));
9022 cast<GEPOperator>(GEP)->setIsInBounds(true);
9023 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00009024 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009025 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009026
Eli Friedman2451a642009-07-18 23:06:53 +00009027 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9028 if (DestVTy->getNumElements() == 1) {
9029 if (!isa<VectorType>(SrcTy)) {
9030 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9031 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009032 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00009033 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009034 }
9035 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9036 }
9037 }
9038
9039 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9040 if (SrcVTy->getNumElements() == 1) {
9041 if (!isa<VectorType>(DestTy)) {
9042 Instruction *Elem =
Owen Anderson1d0be152009-08-13 21:58:54 +00009043 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009044 InsertNewInstBefore(Elem, CI);
9045 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9046 }
9047 }
9048 }
9049
Reid Spencer3da59db2006-11-27 01:05:10 +00009050 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9051 if (SVI->hasOneUse()) {
9052 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9053 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009054 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009055 cast<VectorType>(DestTy)->getNumElements() ==
9056 SVI->getType()->getNumElements() &&
9057 SVI->getType()->getNumElements() ==
9058 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009059 CastInst *Tmp;
9060 // If either of the operands is a cast from CI.getType(), then
9061 // evaluating the shuffle in the casted destination's type will allow
9062 // us to eliminate at least one cast.
9063 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9064 Tmp->getOperand(0)->getType() == DestTy) ||
9065 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9066 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009067 Value *LHS = InsertCastBefore(Instruction::BitCast,
9068 SVI->getOperand(0), DestTy, CI);
9069 Value *RHS = InsertCastBefore(Instruction::BitCast,
9070 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009071 // Return a new shuffle vector. Use the same element ID's, as we
9072 // know the vector types match #elts.
9073 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009074 }
9075 }
9076 }
9077 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009078 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009079}
9080
Chris Lattnere576b912004-04-09 23:46:01 +00009081/// GetSelectFoldableOperands - We want to turn code that looks like this:
9082/// %C = or %A, %B
9083/// %D = select %cond, %C, %A
9084/// into:
9085/// %C = select %cond, %B, 0
9086/// %D = or %A, %C
9087///
9088/// Assuming that the specified instruction is an operand to the select, return
9089/// a bitmask indicating which operands of this instruction are foldable if they
9090/// equal the other incoming value of the select.
9091///
9092static unsigned GetSelectFoldableOperands(Instruction *I) {
9093 switch (I->getOpcode()) {
9094 case Instruction::Add:
9095 case Instruction::Mul:
9096 case Instruction::And:
9097 case Instruction::Or:
9098 case Instruction::Xor:
9099 return 3; // Can fold through either operand.
9100 case Instruction::Sub: // Can only fold on the amount subtracted.
9101 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009102 case Instruction::LShr:
9103 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009104 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009105 default:
9106 return 0; // Cannot fold
9107 }
9108}
9109
9110/// GetSelectFoldableConstant - For the same transformation as the previous
9111/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009112static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009113 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009114 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009115 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009116 case Instruction::Add:
9117 case Instruction::Sub:
9118 case Instruction::Or:
9119 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009120 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009121 case Instruction::LShr:
9122 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009123 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009124 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009125 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009126 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009127 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009128 }
9129}
9130
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009131/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9132/// have the same opcode and only one use each. Try to simplify this.
9133Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9134 Instruction *FI) {
9135 if (TI->getNumOperands() == 1) {
9136 // If this is a non-volatile load or a cast from the same type,
9137 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009138 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009139 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9140 return 0;
9141 } else {
9142 return 0; // unknown unary op.
9143 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009144
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009145 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009146 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009147 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009148 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009149 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009150 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009151 }
9152
Reid Spencer832254e2007-02-02 02:16:23 +00009153 // Only handle binary operators here.
9154 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009155 return 0;
9156
9157 // Figure out if the operations have any operands in common.
9158 Value *MatchOp, *OtherOpT, *OtherOpF;
9159 bool MatchIsOpZero;
9160 if (TI->getOperand(0) == FI->getOperand(0)) {
9161 MatchOp = TI->getOperand(0);
9162 OtherOpT = TI->getOperand(1);
9163 OtherOpF = FI->getOperand(1);
9164 MatchIsOpZero = true;
9165 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9166 MatchOp = TI->getOperand(1);
9167 OtherOpT = TI->getOperand(0);
9168 OtherOpF = FI->getOperand(0);
9169 MatchIsOpZero = false;
9170 } else if (!TI->isCommutative()) {
9171 return 0;
9172 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9173 MatchOp = TI->getOperand(0);
9174 OtherOpT = TI->getOperand(1);
9175 OtherOpF = FI->getOperand(0);
9176 MatchIsOpZero = true;
9177 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9178 MatchOp = TI->getOperand(1);
9179 OtherOpT = TI->getOperand(0);
9180 OtherOpF = FI->getOperand(1);
9181 MatchIsOpZero = true;
9182 } else {
9183 return 0;
9184 }
9185
9186 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009187 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9188 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009189 InsertNewInstBefore(NewSI, SI);
9190
9191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9192 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009193 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009194 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009195 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009196 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009197 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009198 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009199}
9200
Evan Chengde621922009-03-31 20:42:45 +00009201static bool isSelect01(Constant *C1, Constant *C2) {
9202 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9203 if (!C1I)
9204 return false;
9205 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9206 if (!C2I)
9207 return false;
9208 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9209}
9210
9211/// FoldSelectIntoOp - Try fold the select into one of the operands to
9212/// facilitate further optimization.
9213Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9214 Value *FalseVal) {
9215 // See the comment above GetSelectFoldableOperands for a description of the
9216 // transformation we are doing here.
9217 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9218 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9219 !isa<Constant>(FalseVal)) {
9220 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9221 unsigned OpToFold = 0;
9222 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9223 OpToFold = 1;
9224 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9225 OpToFold = 2;
9226 }
9227
9228 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009229 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009230 Value *OOp = TVI->getOperand(2-OpToFold);
9231 // Avoid creating select between 2 constants unless it's selecting
9232 // between 0 and 1.
9233 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9234 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9235 InsertNewInstBefore(NewSel, SI);
9236 NewSel->takeName(TVI);
9237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9238 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009239 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009240 }
9241 }
9242 }
9243 }
9244 }
9245
9246 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9247 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9248 !isa<Constant>(TrueVal)) {
9249 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9250 unsigned OpToFold = 0;
9251 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9252 OpToFold = 1;
9253 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9254 OpToFold = 2;
9255 }
9256
9257 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009258 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009259 Value *OOp = FVI->getOperand(2-OpToFold);
9260 // Avoid creating select between 2 constants unless it's selecting
9261 // between 0 and 1.
9262 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9263 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9264 InsertNewInstBefore(NewSel, SI);
9265 NewSel->takeName(FVI);
9266 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9267 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009268 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009269 }
9270 }
9271 }
9272 }
9273 }
9274
9275 return 0;
9276}
9277
Dan Gohman81b28ce2008-09-16 18:46:06 +00009278/// visitSelectInstWithICmp - Visit a SelectInst that has an
9279/// ICmpInst as its first operand.
9280///
9281Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9282 ICmpInst *ICI) {
9283 bool Changed = false;
9284 ICmpInst::Predicate Pred = ICI->getPredicate();
9285 Value *CmpLHS = ICI->getOperand(0);
9286 Value *CmpRHS = ICI->getOperand(1);
9287 Value *TrueVal = SI.getTrueValue();
9288 Value *FalseVal = SI.getFalseValue();
9289
9290 // Check cases where the comparison is with a constant that
9291 // can be adjusted to fit the min/max idiom. We may edit ICI in
9292 // place here, so make sure the select is the only user.
9293 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009294 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009295 switch (Pred) {
9296 default: break;
9297 case ICmpInst::ICMP_ULT:
9298 case ICmpInst::ICMP_SLT: {
9299 // X < MIN ? T : F --> F
9300 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9301 return ReplaceInstUsesWith(SI, FalseVal);
9302 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009303 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009304 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9305 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9306 Pred = ICmpInst::getSwappedPredicate(Pred);
9307 CmpRHS = AdjustedRHS;
9308 std::swap(FalseVal, TrueVal);
9309 ICI->setPredicate(Pred);
9310 ICI->setOperand(1, CmpRHS);
9311 SI.setOperand(1, TrueVal);
9312 SI.setOperand(2, FalseVal);
9313 Changed = true;
9314 }
9315 break;
9316 }
9317 case ICmpInst::ICMP_UGT:
9318 case ICmpInst::ICMP_SGT: {
9319 // X > MAX ? T : F --> F
9320 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9321 return ReplaceInstUsesWith(SI, FalseVal);
9322 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009323 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009324 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9325 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9326 Pred = ICmpInst::getSwappedPredicate(Pred);
9327 CmpRHS = AdjustedRHS;
9328 std::swap(FalseVal, TrueVal);
9329 ICI->setPredicate(Pred);
9330 ICI->setOperand(1, CmpRHS);
9331 SI.setOperand(1, TrueVal);
9332 SI.setOperand(2, FalseVal);
9333 Changed = true;
9334 }
9335 break;
9336 }
9337 }
9338
Dan Gohman1975d032008-10-30 20:40:10 +00009339 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9340 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009341 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009342 if (match(TrueVal, m_ConstantInt<-1>()) &&
9343 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009344 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009345 else if (match(TrueVal, m_ConstantInt<0>()) &&
9346 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009347 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9348
Dan Gohman1975d032008-10-30 20:40:10 +00009349 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9350 // If we are just checking for a icmp eq of a single bit and zext'ing it
9351 // to an integer, then shift the bit to the appropriate place and then
9352 // cast to integer to avoid the comparison.
9353 const APInt &Op1CV = CI->getValue();
9354
9355 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9356 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9357 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009358 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009359 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009360 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009361 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009362 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009363 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009364 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009365 if (In->getType() != SI.getType())
9366 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009367 true/*SExt*/, "tmp", ICI);
9368
9369 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009370 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009371 In->getName()+".not"), *ICI);
9372
9373 return ReplaceInstUsesWith(SI, In);
9374 }
9375 }
9376 }
9377
Dan Gohman81b28ce2008-09-16 18:46:06 +00009378 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9379 // Transform (X == Y) ? X : Y -> Y
9380 if (Pred == ICmpInst::ICMP_EQ)
9381 return ReplaceInstUsesWith(SI, FalseVal);
9382 // Transform (X != Y) ? X : Y -> X
9383 if (Pred == ICmpInst::ICMP_NE)
9384 return ReplaceInstUsesWith(SI, TrueVal);
9385 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9386
9387 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9388 // Transform (X == Y) ? Y : X -> X
9389 if (Pred == ICmpInst::ICMP_EQ)
9390 return ReplaceInstUsesWith(SI, FalseVal);
9391 // Transform (X != Y) ? Y : X -> Y
9392 if (Pred == ICmpInst::ICMP_NE)
9393 return ReplaceInstUsesWith(SI, TrueVal);
9394 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9395 }
9396
9397 /// NOTE: if we wanted to, this is where to detect integer ABS
9398
9399 return Changed ? &SI : 0;
9400}
9401
Chris Lattner3d69f462004-03-12 05:52:32 +00009402Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009403 Value *CondVal = SI.getCondition();
9404 Value *TrueVal = SI.getTrueValue();
9405 Value *FalseVal = SI.getFalseValue();
9406
9407 // select true, X, Y -> X
9408 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009409 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009410 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009411
9412 // select C, X, X -> X
9413 if (TrueVal == FalseVal)
9414 return ReplaceInstUsesWith(SI, TrueVal);
9415
Chris Lattnere87597f2004-10-16 18:11:37 +00009416 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9417 return ReplaceInstUsesWith(SI, FalseVal);
9418 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9419 return ReplaceInstUsesWith(SI, TrueVal);
9420 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9421 if (isa<Constant>(TrueVal))
9422 return ReplaceInstUsesWith(SI, TrueVal);
9423 else
9424 return ReplaceInstUsesWith(SI, FalseVal);
9425 }
9426
Owen Anderson1d0be152009-08-13 21:58:54 +00009427 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009428 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009429 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009430 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009431 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009432 } else {
9433 // Change: A = select B, false, C --> A = and !B, C
9434 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009435 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009436 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009438 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009439 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009440 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009441 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009442 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009443 } else {
9444 // Change: A = select B, C, true --> A = or !B, C
9445 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009446 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009447 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009448 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009449 }
9450 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009451
9452 // select a, b, a -> a&b
9453 // select a, a, b -> a|b
9454 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009455 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009456 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009457 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009458 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009459
Chris Lattner2eefe512004-04-09 19:05:30 +00009460 // Selecting between two integer constants?
9461 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9462 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009463 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009464 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009465 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009466 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009467 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009468 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009469 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009470 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009471 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009472 }
Chris Lattner457dd822004-06-09 07:59:58 +00009473
Reid Spencere4d87aa2006-12-23 06:05:41 +00009474 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009475 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009476 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009477 // non-constant value, eliminate this whole mess. This corresponds to
9478 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009479 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009480 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009481 cast<Constant>(IC->getOperand(1))->isNullValue())
9482 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9483 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009484 isa<ConstantInt>(ICA->getOperand(1)) &&
9485 (ICA->getOperand(1) == TrueValC ||
9486 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009487 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9488 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009489 // know whether we have a icmp_ne or icmp_eq and whether the
9490 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009491 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009492 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009493 Value *V = ICA;
9494 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009495 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009496 Instruction::Xor, V, ICA->getOperand(1)), SI);
9497 return ReplaceInstUsesWith(SI, V);
9498 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009499 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009500 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009501
9502 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009503 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9504 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009505 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009506 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9507 // This is not safe in general for floating point:
9508 // consider X== -0, Y== +0.
9509 // It becomes safe if either operand is a nonzero constant.
9510 ConstantFP *CFPt, *CFPf;
9511 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9512 !CFPt->getValueAPF().isZero()) ||
9513 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9514 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009515 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009516 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009517 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009518 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009519 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009520 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009521
Reid Spencere4d87aa2006-12-23 06:05:41 +00009522 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009523 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009524 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9525 // This is not safe in general for floating point:
9526 // consider X== -0, Y== +0.
9527 // It becomes safe if either operand is a nonzero constant.
9528 ConstantFP *CFPt, *CFPf;
9529 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9530 !CFPt->getValueAPF().isZero()) ||
9531 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9532 !CFPf->getValueAPF().isZero()))
9533 return ReplaceInstUsesWith(SI, FalseVal);
9534 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009535 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009536 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9537 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009538 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009539 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009540 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009541 }
9542
9543 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009544 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9545 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9546 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009547
Chris Lattner87875da2005-01-13 22:52:24 +00009548 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9549 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9550 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009551 Instruction *AddOp = 0, *SubOp = 0;
9552
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009553 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9554 if (TI->getOpcode() == FI->getOpcode())
9555 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9556 return IV;
9557
9558 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9559 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009560 if ((TI->getOpcode() == Instruction::Sub &&
9561 FI->getOpcode() == Instruction::Add) ||
9562 (TI->getOpcode() == Instruction::FSub &&
9563 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009564 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009565 } else if ((FI->getOpcode() == Instruction::Sub &&
9566 TI->getOpcode() == Instruction::Add) ||
9567 (FI->getOpcode() == Instruction::FSub &&
9568 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009569 AddOp = TI; SubOp = FI;
9570 }
9571
9572 if (AddOp) {
9573 Value *OtherAddOp = 0;
9574 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9575 OtherAddOp = AddOp->getOperand(1);
9576 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9577 OtherAddOp = AddOp->getOperand(0);
9578 }
9579
9580 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009581 // So at this point we know we have (Y -> OtherAddOp):
9582 // select C, (add X, Y), (sub X, Z)
9583 Value *NegVal; // Compute -Z
9584 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009585 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009586 } else {
9587 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009588 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009589 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009590 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009591
9592 Value *NewTrueOp = OtherAddOp;
9593 Value *NewFalseOp = NegVal;
9594 if (AddOp != TI)
9595 std::swap(NewTrueOp, NewFalseOp);
9596 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009597 SelectInst::Create(CondVal, NewTrueOp,
9598 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009599
9600 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009601 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009602 }
9603 }
9604 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009605
Chris Lattnere576b912004-04-09 23:46:01 +00009606 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009607 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009608 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9609 if (FoldI)
9610 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009611 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009612
9613 if (BinaryOperator::isNot(CondVal)) {
9614 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9615 SI.setOperand(1, FalseVal);
9616 SI.setOperand(2, TrueVal);
9617 return &SI;
9618 }
9619
Chris Lattner3d69f462004-03-12 05:52:32 +00009620 return 0;
9621}
9622
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623/// EnforceKnownAlignment - If the specified pointer points to an object that
9624/// we control, modify the object's alignment to PrefAlign. This isn't
9625/// often possible though. If alignment is important, a more reliable approach
9626/// is to simply align all global variables and allocation instructions to
9627/// their preferred alignment from the beginning.
9628///
9629static unsigned EnforceKnownAlignment(Value *V,
9630 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009631
Dan Gohmaneee962e2008-04-10 18:43:06 +00009632 User *U = dyn_cast<User>(V);
9633 if (!U) return Align;
9634
Dan Gohmanca178902009-07-17 20:47:02 +00009635 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009636 default: break;
9637 case Instruction::BitCast:
9638 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9639 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009640 // If all indexes are zero, it is just the alignment of the base pointer.
9641 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009642 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009643 if (!isa<Constant>(*i) ||
9644 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009645 AllZeroOperands = false;
9646 break;
9647 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009648
9649 if (AllZeroOperands) {
9650 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009651 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009652 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009653 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009654 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009655 }
9656
9657 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9658 // If there is a large requested alignment and we can, bump up the alignment
9659 // of the global.
9660 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009661 if (GV->getAlignment() >= PrefAlign)
9662 Align = GV->getAlignment();
9663 else {
9664 GV->setAlignment(PrefAlign);
9665 Align = PrefAlign;
9666 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009667 }
9668 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9669 // If there is a requested alignment and if this is an alloca, round up. We
9670 // don't do this for malloc, because some systems can't respect the request.
9671 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009672 if (AI->getAlignment() >= PrefAlign)
9673 Align = AI->getAlignment();
9674 else {
9675 AI->setAlignment(PrefAlign);
9676 Align = PrefAlign;
9677 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009678 }
9679 }
9680
9681 return Align;
9682}
9683
9684/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9685/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9686/// and it is more than the alignment of the ultimate object, see if we can
9687/// increase the alignment of the ultimate object, making this check succeed.
9688unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9689 unsigned PrefAlign) {
9690 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9691 sizeof(PrefAlign) * CHAR_BIT;
9692 APInt Mask = APInt::getAllOnesValue(BitWidth);
9693 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9694 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9695 unsigned TrailZ = KnownZero.countTrailingOnes();
9696 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9697
9698 if (PrefAlign > Align)
9699 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9700
9701 // We don't need to make any adjustment.
9702 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009703}
9704
Chris Lattnerf497b022008-01-13 23:50:23 +00009705Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009706 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009707 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009708 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009709 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009710
9711 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009712 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009713 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009714 return MI;
9715 }
9716
9717 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9718 // load/store.
9719 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9720 if (MemOpLength == 0) return 0;
9721
Chris Lattner37ac6082008-01-14 00:28:35 +00009722 // Source and destination pointer types are always "i8*" for intrinsic. See
9723 // if the size is something we can handle with a single primitive load/store.
9724 // A single load+store correctly handles overlapping memory in the memmove
9725 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009726 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009727 if (Size == 0) return MI; // Delete this mem transfer.
9728
9729 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009730 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009731
Chris Lattner37ac6082008-01-14 00:28:35 +00009732 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009733 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009734 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009735
9736 // Memcpy forces the use of i8* for the source and destination. That means
9737 // that if you're using memcpy to move one double around, you'll get a cast
9738 // from double* to i8*. We'd much rather use a double load+store rather than
9739 // an i64 load+store, here because this improves the odds that the source or
9740 // dest address will be promotable. See if we can find a better type than the
9741 // integer datatype.
9742 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9743 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009744 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009745 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9746 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009747 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009748 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9749 if (STy->getNumElements() == 1)
9750 SrcETy = STy->getElementType(0);
9751 else
9752 break;
9753 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9754 if (ATy->getNumElements() == 1)
9755 SrcETy = ATy->getElementType();
9756 else
9757 break;
9758 } else
9759 break;
9760 }
9761
Dan Gohman8f8e2692008-05-23 01:52:21 +00009762 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009763 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009764 }
9765 }
9766
9767
Chris Lattnerf497b022008-01-13 23:50:23 +00009768 // If the memcpy/memmove provides better alignment info than we can
9769 // infer, use it.
9770 SrcAlign = std::max(SrcAlign, CopyAlign);
9771 DstAlign = std::max(DstAlign, CopyAlign);
9772
9773 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9774 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009775 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9776 InsertNewInstBefore(L, *MI);
9777 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9778
9779 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009780 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009781 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009782}
Chris Lattner3d69f462004-03-12 05:52:32 +00009783
Chris Lattner69ea9d22008-04-30 06:39:11 +00009784Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9785 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009786 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009787 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009788 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009789 return MI;
9790 }
9791
9792 // Extract the length and alignment and fill if they are constant.
9793 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9794 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009795 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009796 return 0;
9797 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009798 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009799
9800 // If the length is zero, this is a no-op
9801 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9802
9803 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9804 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009805 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009806
9807 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009808 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009809
9810 // Alignment 0 is identity for alignment 1 for memset, but not store.
9811 if (Alignment == 0) Alignment = 1;
9812
9813 // Extract the fill value and store.
9814 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009815 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009816 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009817
9818 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009819 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009820 return MI;
9821 }
9822
9823 return 0;
9824}
9825
9826
Chris Lattner8b0ea312006-01-13 20:11:04 +00009827/// visitCallInst - CallInst simplification. This mostly only handles folding
9828/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9829/// the heavy lifting.
9830///
Chris Lattner9fe38862003-06-19 17:00:31 +00009831Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009832 // If the caller function is nounwind, mark the call as nounwind, even if the
9833 // callee isn't.
9834 if (CI.getParent()->getParent()->doesNotThrow() &&
9835 !CI.doesNotThrow()) {
9836 CI.setDoesNotThrow();
9837 return &CI;
9838 }
9839
9840
9841
Chris Lattner8b0ea312006-01-13 20:11:04 +00009842 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9843 if (!II) return visitCallSite(&CI);
9844
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009845 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9846 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009847 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009848 bool Changed = false;
9849
9850 // memmove/cpy/set of zero bytes is a noop.
9851 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9852 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9853
Chris Lattner35b9e482004-10-12 04:52:52 +00009854 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009855 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009856 // Replace the instruction with just byte operations. We would
9857 // transform other cases to loads/stores, but we don't know if
9858 // alignment is sufficient.
9859 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009860 }
9861
Chris Lattner35b9e482004-10-12 04:52:52 +00009862 // If we have a memmove and the source operation is a constant global,
9863 // then the source and dest pointers can't alias, so we can change this
9864 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009865 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009866 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9867 if (GVSrc->isConstant()) {
9868 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009869 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9870 const Type *Tys[1];
9871 Tys[0] = CI.getOperand(3)->getType();
9872 CI.setOperand(0,
9873 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009874 Changed = true;
9875 }
Chris Lattnera935db82008-05-28 05:30:41 +00009876
9877 // memmove(x,x,size) -> noop.
9878 if (MMI->getSource() == MMI->getDest())
9879 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009880 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009881
Chris Lattner95a959d2006-03-06 20:18:44 +00009882 // If we can determine a pointer alignment that is bigger than currently
9883 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009884 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009885 if (Instruction *I = SimplifyMemTransfer(MI))
9886 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009887 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9888 if (Instruction *I = SimplifyMemSet(MSI))
9889 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009890 }
9891
Chris Lattner8b0ea312006-01-13 20:11:04 +00009892 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009893 }
9894
9895 switch (II->getIntrinsicID()) {
9896 default: break;
9897 case Intrinsic::bswap:
9898 // bswap(bswap(x)) -> x
9899 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9900 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9901 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9902 break;
9903 case Intrinsic::ppc_altivec_lvx:
9904 case Intrinsic::ppc_altivec_lvxl:
9905 case Intrinsic::x86_sse_loadu_ps:
9906 case Intrinsic::x86_sse2_loadu_pd:
9907 case Intrinsic::x86_sse2_loadu_dq:
9908 // Turn PPC lvx -> load if the pointer is known aligned.
9909 // Turn X86 loadups -> load if the pointer is known aligned.
9910 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9911 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009912 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009913 CI);
9914 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009915 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009916 break;
9917 case Intrinsic::ppc_altivec_stvx:
9918 case Intrinsic::ppc_altivec_stvxl:
9919 // Turn stvx -> store if the pointer is known aligned.
9920 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9921 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009922 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009923 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9924 return new StoreInst(II->getOperand(1), Ptr);
9925 }
9926 break;
9927 case Intrinsic::x86_sse_storeu_ps:
9928 case Intrinsic::x86_sse2_storeu_pd:
9929 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 // Turn X86 storeu -> store if the pointer is known aligned.
9931 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9932 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009933 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009934 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9935 return new StoreInst(II->getOperand(2), Ptr);
9936 }
9937 break;
9938
9939 case Intrinsic::x86_sse_cvttss2si: {
9940 // These intrinsics only demands the 0th element of its input vector. If
9941 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009942 unsigned VWidth =
9943 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9944 APInt DemandedElts(VWidth, 1);
9945 APInt UndefElts(VWidth, 0);
9946 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009947 UndefElts)) {
9948 II->setOperand(1, V);
9949 return II;
9950 }
9951 break;
9952 }
9953
9954 case Intrinsic::ppc_altivec_vperm:
9955 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9956 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9957 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009958
Chris Lattner0521e3c2008-06-18 04:33:20 +00009959 // Check that all of the elements are integer constants or undefs.
9960 bool AllEltsOk = true;
9961 for (unsigned i = 0; i != 16; ++i) {
9962 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9963 !isa<UndefValue>(Mask->getOperand(i))) {
9964 AllEltsOk = false;
9965 break;
9966 }
9967 }
9968
9969 if (AllEltsOk) {
9970 // Cast the input vectors to byte vectors.
9971 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9972 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009973 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009974
Chris Lattner0521e3c2008-06-18 04:33:20 +00009975 // Only extract each element once.
9976 Value *ExtractedElts[32];
9977 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9978
Chris Lattnere2ed0572006-04-06 19:19:17 +00009979 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009980 if (isa<UndefValue>(Mask->getOperand(i)))
9981 continue;
9982 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9983 Idx &= 31; // Match the hardware behavior.
9984
9985 if (ExtractedElts[Idx] == 0) {
9986 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009987 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Anderson1d0be152009-08-13 21:58:54 +00009988 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009989 InsertNewInstBefore(Elt, CI);
9990 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009991 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009992
Chris Lattner0521e3c2008-06-18 04:33:20 +00009993 // Insert this value into the result vector.
9994 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson1d0be152009-08-13 21:58:54 +00009995 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009996 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009997 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009998 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009999 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010000 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010001 }
10002 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010003
Chris Lattner0521e3c2008-06-18 04:33:20 +000010004 case Intrinsic::stackrestore: {
10005 // If the save is right next to the restore, remove the restore. This can
10006 // happen when variable allocas are DCE'd.
10007 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10008 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10009 BasicBlock::iterator BI = SS;
10010 if (&*++BI == II)
10011 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010012 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010013 }
10014
10015 // Scan down this block to see if there is another stack restore in the
10016 // same block without an intervening call/alloca.
10017 BasicBlock::iterator BI = II;
10018 TerminatorInst *TI = II->getParent()->getTerminator();
10019 bool CannotRemove = false;
10020 for (++BI; &*BI != TI; ++BI) {
10021 if (isa<AllocaInst>(BI)) {
10022 CannotRemove = true;
10023 break;
10024 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010025 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10026 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10027 // If there is a stackrestore below this one, remove this one.
10028 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10029 return EraseInstFromFunction(CI);
10030 // Otherwise, ignore the intrinsic.
10031 } else {
10032 // If we found a non-intrinsic call, we can't remove the stack
10033 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010034 CannotRemove = true;
10035 break;
10036 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010037 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010038 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010039
10040 // If the stack restore is in a return/unwind block and if there are no
10041 // allocas or calls between the restore and the return, nuke the restore.
10042 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10043 return EraseInstFromFunction(CI);
10044 break;
10045 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010046 }
10047
Chris Lattner8b0ea312006-01-13 20:11:04 +000010048 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010049}
10050
10051// InvokeInst simplification
10052//
10053Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010054 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010055}
10056
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010057/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10058/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010059static bool isSafeToEliminateVarargsCast(const CallSite CS,
10060 const CastInst * const CI,
10061 const TargetData * const TD,
10062 const int ix) {
10063 if (!CI->isLosslessCast())
10064 return false;
10065
10066 // The size of ByVal arguments is derived from the type, so we
10067 // can't change to a type with a different size. If the size were
10068 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010069 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010070 return true;
10071
10072 const Type* SrcTy =
10073 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10074 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10075 if (!SrcTy->isSized() || !DstTy->isSized())
10076 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010077 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010078 return false;
10079 return true;
10080}
10081
Chris Lattnera44d8a22003-10-07 22:32:43 +000010082// visitCallSite - Improvements for call and invoke instructions.
10083//
10084Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010085 bool Changed = false;
10086
10087 // If the callee is a constexpr cast of a function, attempt to move the cast
10088 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010089 if (transformConstExprCastCall(CS)) return 0;
10090
Chris Lattner6c266db2003-10-07 22:54:13 +000010091 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010092
Chris Lattner08b22ec2005-05-13 07:09:09 +000010093 if (Function *CalleeF = dyn_cast<Function>(Callee))
10094 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10095 Instruction *OldCall = CS.getInstruction();
10096 // If the call and callee calling conventions don't match, this call must
10097 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010098 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010099 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +000010100 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010101 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010102 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010103 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10104 return EraseInstFromFunction(*OldCall);
10105 return 0;
10106 }
10107
Chris Lattner17be6352004-10-18 02:59:09 +000010108 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10109 // This instruction is not reachable, just remove it. We insert a store to
10110 // undef so that we know that this code is not reachable, despite the fact
10111 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010112 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010113 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +000010114 CS.getInstruction());
10115
10116 if (!CS.getInstruction()->use_empty())
10117 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010118 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010119
10120 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10121 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010122 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010123 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010124 }
Chris Lattner17be6352004-10-18 02:59:09 +000010125 return EraseInstFromFunction(*CS.getInstruction());
10126 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010127
Duncan Sandscdb6d922007-09-17 10:26:40 +000010128 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10129 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10130 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10131 return transformCallThroughTrampoline(CS);
10132
Chris Lattner6c266db2003-10-07 22:54:13 +000010133 const PointerType *PTy = cast<PointerType>(Callee->getType());
10134 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10135 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010136 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010137 // See if we can optimize any arguments passed through the varargs area of
10138 // the call.
10139 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010140 E = CS.arg_end(); I != E; ++I, ++ix) {
10141 CastInst *CI = dyn_cast<CastInst>(*I);
10142 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10143 *I = CI->getOperand(0);
10144 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010145 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010146 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010147 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010148
Duncan Sandsf0c33542007-12-19 21:13:37 +000010149 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010150 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010151 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010152 Changed = true;
10153 }
10154
Chris Lattner6c266db2003-10-07 22:54:13 +000010155 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010156}
10157
Chris Lattner9fe38862003-06-19 17:00:31 +000010158// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10159// attempt to move the cast to the arguments of the call/invoke.
10160//
10161bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10162 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10163 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010164 if (CE->getOpcode() != Instruction::BitCast ||
10165 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010166 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010167 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010168 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010169 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010170
10171 // Okay, this is a cast from a function to a different type. Unless doing so
10172 // would cause a type conversion of one of our arguments, change this call to
10173 // be a direct call with arguments casted to the appropriate types.
10174 //
10175 const FunctionType *FT = Callee->getFunctionType();
10176 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010177 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010178
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010179 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010180 return false; // TODO: Handle multiple return values.
10181
Chris Lattnerf78616b2004-01-14 06:06:08 +000010182 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010183 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010184 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010185 // Conversion is ok if changing from one pointer type to another or from
10186 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010187 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010188 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010189 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010190 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010191 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010192
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010193 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010194 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010195 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010196 return false; // Cannot transform this return value.
10197
Chris Lattner58d74912008-03-12 17:45:29 +000010198 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010199 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010200 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010201 return false; // Attribute not compatible with transformed value.
10202 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010203
Chris Lattnerf78616b2004-01-14 06:06:08 +000010204 // If the callsite is an invoke instruction, and the return value is used by
10205 // a PHI node in a successor, we cannot change the return type of the call
10206 // because there is no place to put the cast instruction (without breaking
10207 // the critical edge). Bail out in this case.
10208 if (!Caller->use_empty())
10209 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10210 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10211 UI != E; ++UI)
10212 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10213 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010214 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010215 return false;
10216 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010217
10218 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10219 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010220
Chris Lattner9fe38862003-06-19 17:00:31 +000010221 CallSite::arg_iterator AI = CS.arg_begin();
10222 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10223 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010224 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010225
10226 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010227 return false; // Cannot transform this parameter value.
10228
Devang Patel19c87462008-09-26 22:53:05 +000010229 if (CallerPAL.getParamAttributes(i + 1)
10230 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010231 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010232
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010233 // Converting from one pointer type to another or between a pointer and an
10234 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010235 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010236 (TD && ((isa<PointerType>(ParamTy) ||
10237 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10238 (isa<PointerType>(ActTy) ||
10239 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010240 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010241 }
10242
10243 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010244 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010245 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010246
Chris Lattner58d74912008-03-12 17:45:29 +000010247 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10248 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010249 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010250 // won't be dropping them. Check that these extra arguments have attributes
10251 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010252 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10253 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010254 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010255 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010256 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010257 return false;
10258 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010259
Chris Lattner9fe38862003-06-19 17:00:31 +000010260 // Okay, we decided that this is a safe thing to do: go ahead and start
10261 // inserting cast instructions as necessary...
10262 std::vector<Value*> Args;
10263 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010264 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010265 attrVec.reserve(NumCommonArgs);
10266
10267 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010268 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010269
10270 // If the return value is not being used, the type may not be compatible
10271 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010272 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010273
10274 // Add the new return attributes.
10275 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010276 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010277
10278 AI = CS.arg_begin();
10279 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10280 const Type *ParamTy = FT->getParamType(i);
10281 if ((*AI)->getType() == ParamTy) {
10282 Args.push_back(*AI);
10283 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010284 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010285 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010286 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010287 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010288 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010289
10290 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010291 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010292 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010293 }
10294
10295 // If the function takes more arguments than the call was taking, add them
10296 // now...
10297 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010298 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010299
10300 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010301 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010302 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010303 errs() << "WARNING: While resolving call to function '"
10304 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010305 } else {
10306 // Add all of the arguments in their promoted form to the arg list...
10307 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10308 const Type *PTy = getPromotedType((*AI)->getType());
10309 if (PTy != (*AI)->getType()) {
10310 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010311 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10312 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010313 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010314 InsertNewInstBefore(Cast, *Caller);
10315 Args.push_back(Cast);
10316 } else {
10317 Args.push_back(*AI);
10318 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010319
Duncan Sandse1e520f2008-01-13 08:02:44 +000010320 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010321 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010322 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010323 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010324 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010325 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010326
Devang Patel19c87462008-09-26 22:53:05 +000010327 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10328 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10329
Owen Anderson1d0be152009-08-13 21:58:54 +000010330 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010331 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010332
Eric Christophera66297a2009-07-25 02:45:27 +000010333 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10334 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010335
Chris Lattner9fe38862003-06-19 17:00:31 +000010336 Instruction *NC;
10337 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010338 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010339 Args.begin(), Args.end(),
10340 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010341 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010342 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010343 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010344 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10345 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010346 CallInst *CI = cast<CallInst>(Caller);
10347 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010348 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010349 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010350 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010351 }
10352
Chris Lattner6934a042007-02-11 01:23:03 +000010353 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010354 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010355 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010356 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010357 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010358 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010359 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010360
10361 // If this is an invoke instruction, we should insert it after the first
10362 // non-phi, instruction in the normal successor block.
10363 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010364 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010365 InsertNewInstBefore(NC, *I);
10366 } else {
10367 // Otherwise, it's a call, just insert cast right after the call instr
10368 InsertNewInstBefore(NC, *Caller);
10369 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010370 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010371 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010372 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010373 }
10374 }
10375
Owen Anderson1d0be152009-08-13 21:58:54 +000010376 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010377 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010378 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010379 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010380 return true;
10381}
10382
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383// transformCallThroughTrampoline - Turn a call to a function created by the
10384// init_trampoline intrinsic into a direct call to the underlying function.
10385//
10386Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10387 Value *Callee = CS.getCalledValue();
10388 const PointerType *PTy = cast<PointerType>(Callee->getType());
10389 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010390 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010391
10392 // If the call already has the 'nest' attribute somewhere then give up -
10393 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010394 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396
10397 IntrinsicInst *Tramp =
10398 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10399
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010400 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10402 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10403
Devang Patel05988662008-09-25 21:00:45 +000010404 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010405 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406 unsigned NestIdx = 1;
10407 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010408 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409
10410 // Look for a parameter marked with the 'nest' attribute.
10411 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10412 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010413 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414 // Record the parameter type and any other attributes.
10415 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010416 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010417 break;
10418 }
10419
10420 if (NestTy) {
10421 Instruction *Caller = CS.getInstruction();
10422 std::vector<Value*> NewArgs;
10423 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10424
Devang Patel05988662008-09-25 21:00:45 +000010425 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010426 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010427
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010429 // mean appending it. Likewise for attributes.
10430
Devang Patel19c87462008-09-26 22:53:05 +000010431 // Add any result attributes.
10432 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010433 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010434
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 {
10436 unsigned Idx = 1;
10437 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10438 do {
10439 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010440 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010441 Value *NestVal = Tramp->getOperand(3);
10442 if (NestVal->getType() != NestTy)
10443 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10444 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010445 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446 }
10447
10448 if (I == E)
10449 break;
10450
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010451 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010453 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010454 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010455 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010456
10457 ++Idx, ++I;
10458 } while (1);
10459 }
10460
Devang Patel19c87462008-09-26 22:53:05 +000010461 // Add any function attributes.
10462 if (Attributes Attr = Attrs.getFnAttributes())
10463 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10464
Duncan Sandscdb6d922007-09-17 10:26:40 +000010465 // The trampoline may have been bitcast to a bogus type (FTy).
10466 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010467 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010468
Duncan Sandscdb6d922007-09-17 10:26:40 +000010469 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010470 NewTypes.reserve(FTy->getNumParams()+1);
10471
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010473 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010474 {
10475 unsigned Idx = 1;
10476 FunctionType::param_iterator I = FTy->param_begin(),
10477 E = FTy->param_end();
10478
10479 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010480 if (Idx == NestIdx)
10481 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010483
10484 if (I == E)
10485 break;
10486
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010487 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010488 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010489
10490 ++Idx, ++I;
10491 } while (1);
10492 }
10493
10494 // Replace the trampoline call with a direct call. Let the generic
10495 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010496 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010497 FTy->isVarArg());
10498 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010499 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010500 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010501 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010502 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10503 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010504
10505 Instruction *NewCaller;
10506 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010507 NewCaller = InvokeInst::Create(NewCallee,
10508 II->getNormalDest(), II->getUnwindDest(),
10509 NewArgs.begin(), NewArgs.end(),
10510 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010511 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010512 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010513 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010514 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10515 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010516 if (cast<CallInst>(Caller)->isTailCall())
10517 cast<CallInst>(NewCaller)->setTailCall();
10518 cast<CallInst>(NewCaller)->
10519 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010520 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010521 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010522 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010523 Caller->replaceAllUsesWith(NewCaller);
10524 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010525 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010526 return 0;
10527 }
10528 }
10529
10530 // Replace the trampoline call with a direct call. Since there is no 'nest'
10531 // parameter, there is no need to adjust the argument list. Let the generic
10532 // code sort out any function type mismatches.
10533 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010534 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010535 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010536 CS.setCalledFunction(NewCallee);
10537 return CS.getInstruction();
10538}
10539
Chris Lattner7da52b22006-11-01 04:51:18 +000010540/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10541/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10542/// and a single binop.
10543Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10544 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010545 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010546 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010547 Value *LHSVal = FirstInst->getOperand(0);
10548 Value *RHSVal = FirstInst->getOperand(1);
10549
10550 const Type *LHSType = LHSVal->getType();
10551 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010552
10553 // Scan to see if all operands are the same opcode, all have one use, and all
10554 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010555 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010556 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010557 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010558 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010559 // types or GEP's with different index types.
10560 I->getOperand(0)->getType() != LHSType ||
10561 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010562 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010563
10564 // If they are CmpInst instructions, check their predicates
10565 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10566 if (cast<CmpInst>(I)->getPredicate() !=
10567 cast<CmpInst>(FirstInst)->getPredicate())
10568 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010569
10570 // Keep track of which operand needs a phi node.
10571 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10572 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010573 }
10574
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010575 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010576
Chris Lattner7da52b22006-11-01 04:51:18 +000010577 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010578 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010579 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010580 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010581 NewLHS = PHINode::Create(LHSType,
10582 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010583 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10584 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010585 InsertNewInstBefore(NewLHS, PN);
10586 LHSVal = NewLHS;
10587 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010588
10589 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010590 NewRHS = PHINode::Create(RHSType,
10591 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010592 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10593 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010594 InsertNewInstBefore(NewRHS, PN);
10595 RHSVal = NewRHS;
10596 }
10597
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010598 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010599 if (NewLHS || NewRHS) {
10600 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10601 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10602 if (NewLHS) {
10603 Value *NewInLHS = InInst->getOperand(0);
10604 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10605 }
10606 if (NewRHS) {
10607 Value *NewInRHS = InInst->getOperand(1);
10608 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10609 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010610 }
10611 }
10612
Chris Lattner7da52b22006-11-01 04:51:18 +000010613 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010614 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010615 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010616 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010617 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010618}
10619
Chris Lattner05f18922008-12-01 02:34:36 +000010620Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10621 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10622
10623 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10624 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010625 // This is true if all GEP bases are allocas and if all indices into them are
10626 // constants.
10627 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010628
10629 // Scan to see if all operands are the same opcode, all have one use, and all
10630 // kill their operands (i.e. the operands have one use).
10631 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10632 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10633 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10634 GEP->getNumOperands() != FirstInst->getNumOperands())
10635 return 0;
10636
Chris Lattner36d3e322009-02-21 00:46:50 +000010637 // Keep track of whether or not all GEPs are of alloca pointers.
10638 if (AllBasePointersAreAllocas &&
10639 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10640 !GEP->hasAllConstantIndices()))
10641 AllBasePointersAreAllocas = false;
10642
Chris Lattner05f18922008-12-01 02:34:36 +000010643 // Compare the operand lists.
10644 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10645 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10646 continue;
10647
10648 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10649 // if one of the PHIs has a constant for the index. The index may be
10650 // substantially cheaper to compute for the constants, so making it a
10651 // variable index could pessimize the path. This also handles the case
10652 // for struct indices, which must always be constant.
10653 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10654 isa<ConstantInt>(GEP->getOperand(op)))
10655 return 0;
10656
10657 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10658 return 0;
10659 FixedOperands[op] = 0; // Needs a PHI.
10660 }
10661 }
10662
Chris Lattner36d3e322009-02-21 00:46:50 +000010663 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010664 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010665 // offset calculation, but all the predecessors will have to materialize the
10666 // stack address into a register anyway. We'd actually rather *clone* the
10667 // load up into the predecessors so that we have a load of a gep of an alloca,
10668 // which can usually all be folded into the load.
10669 if (AllBasePointersAreAllocas)
10670 return 0;
10671
Chris Lattner05f18922008-12-01 02:34:36 +000010672 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10673 // that is variable.
10674 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10675
10676 bool HasAnyPHIs = false;
10677 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10678 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10679 Value *FirstOp = FirstInst->getOperand(i);
10680 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10681 FirstOp->getName()+".pn");
10682 InsertNewInstBefore(NewPN, PN);
10683
10684 NewPN->reserveOperandSpace(e);
10685 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10686 OperandPhis[i] = NewPN;
10687 FixedOperands[i] = NewPN;
10688 HasAnyPHIs = true;
10689 }
10690
10691
10692 // Add all operands to the new PHIs.
10693 if (HasAnyPHIs) {
10694 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10695 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10696 BasicBlock *InBB = PN.getIncomingBlock(i);
10697
10698 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10699 if (PHINode *OpPhi = OperandPhis[op])
10700 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10701 }
10702 }
10703
10704 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010705 GetElementPtrInst *GEP =
10706 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10707 FixedOperands.end());
10708 if (cast<GEPOperator>(FirstInst)->isInBounds())
10709 cast<GEPOperator>(GEP)->setIsInBounds(true);
10710 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010711}
10712
10713
Chris Lattner21550882009-02-23 05:56:17 +000010714/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10715/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010716/// obvious the value of the load is not changed from the point of the load to
10717/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010718///
10719/// Finally, it is safe, but not profitable, to sink a load targetting a
10720/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10721/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010722static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010723 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10724
10725 for (++BBI; BBI != E; ++BBI)
10726 if (BBI->mayWriteToMemory())
10727 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010728
10729 // Check for non-address taken alloca. If not address-taken already, it isn't
10730 // profitable to do this xform.
10731 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10732 bool isAddressTaken = false;
10733 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10734 UI != E; ++UI) {
10735 if (isa<LoadInst>(UI)) continue;
10736 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10737 // If storing TO the alloca, then the address isn't taken.
10738 if (SI->getOperand(1) == AI) continue;
10739 }
10740 isAddressTaken = true;
10741 break;
10742 }
10743
Chris Lattner36d3e322009-02-21 00:46:50 +000010744 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010745 return false;
10746 }
10747
Chris Lattner36d3e322009-02-21 00:46:50 +000010748 // If this load is a load from a GEP with a constant offset from an alloca,
10749 // then we don't want to sink it. In its present form, it will be
10750 // load [constant stack offset]. Sinking it will cause us to have to
10751 // materialize the stack addresses in each predecessor in a register only to
10752 // do a shared load from register in the successor.
10753 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10754 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10755 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10756 return false;
10757
Chris Lattner76c73142006-11-01 07:13:54 +000010758 return true;
10759}
10760
Chris Lattner9fe38862003-06-19 17:00:31 +000010761
Chris Lattnerbac32862004-11-14 19:13:23 +000010762// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10763// operator and they all are only used by the PHI, PHI together their
10764// inputs, and do the operation once, to the result of the PHI.
10765Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10766 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10767
10768 // Scan the instruction, looking for input operations that can be folded away.
10769 // If all input operands to the phi are the same instruction (e.g. a cast from
10770 // the same type or "+42") we can pull the operation through the PHI, reducing
10771 // code size and simplifying code.
10772 Constant *ConstantOp = 0;
10773 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010774 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010775 if (isa<CastInst>(FirstInst)) {
10776 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010777 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010778 // Can fold binop, compare or shift here if the RHS is a constant,
10779 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010780 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010781 if (ConstantOp == 0)
10782 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010783 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10784 isVolatile = LI->isVolatile();
10785 // We can't sink the load if the loaded value could be modified between the
10786 // load and the PHI.
10787 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010788 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010789 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010790
10791 // If the PHI is of volatile loads and the load block has multiple
10792 // successors, sinking it would remove a load of the volatile value from
10793 // the path through the other successor.
10794 if (isVolatile &&
10795 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10796 return 0;
10797
Chris Lattner9c080502006-11-01 07:43:41 +000010798 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010799 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010800 } else {
10801 return 0; // Cannot fold this operation.
10802 }
10803
10804 // Check to see if all arguments are the same operation.
10805 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10806 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10807 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010808 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010809 return 0;
10810 if (CastSrcTy) {
10811 if (I->getOperand(0)->getType() != CastSrcTy)
10812 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010813 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010814 // We can't sink the load if the loaded value could be modified between
10815 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010816 if (LI->isVolatile() != isVolatile ||
10817 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010818 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010819 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010820
Chris Lattner71042962008-07-08 17:18:32 +000010821 // If the PHI is of volatile loads and the load block has multiple
10822 // successors, sinking it would remove a load of the volatile value from
10823 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010824 if (isVolatile &&
10825 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10826 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010827
Chris Lattnerbac32862004-11-14 19:13:23 +000010828 } else if (I->getOperand(1) != ConstantOp) {
10829 return 0;
10830 }
10831 }
10832
10833 // Okay, they are all the same operation. Create a new PHI node of the
10834 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010835 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10836 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010837 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010838
10839 Value *InVal = FirstInst->getOperand(0);
10840 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010841
10842 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010843 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10844 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10845 if (NewInVal != InVal)
10846 InVal = 0;
10847 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10848 }
10849
10850 Value *PhiVal;
10851 if (InVal) {
10852 // The new PHI unions all of the same values together. This is really
10853 // common, so we handle it intelligently here for compile-time speed.
10854 PhiVal = InVal;
10855 delete NewPN;
10856 } else {
10857 InsertNewInstBefore(NewPN, PN);
10858 PhiVal = NewPN;
10859 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010860
Chris Lattnerbac32862004-11-14 19:13:23 +000010861 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010862 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010863 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010864 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010865 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010866 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010867 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010868 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010869 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10870
10871 // If this was a volatile load that we are merging, make sure to loop through
10872 // and mark all the input loads as non-volatile. If we don't do this, we will
10873 // insert a new volatile load and the old ones will not be deletable.
10874 if (isVolatile)
10875 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10876 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10877
10878 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010879}
Chris Lattnera1be5662002-05-02 17:06:02 +000010880
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010881/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10882/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010883static bool DeadPHICycle(PHINode *PN,
10884 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010885 if (PN->use_empty()) return true;
10886 if (!PN->hasOneUse()) return false;
10887
10888 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010889 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010890 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010891
10892 // Don't scan crazily complex things.
10893 if (PotentiallyDeadPHIs.size() == 16)
10894 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010895
10896 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10897 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010898
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010899 return false;
10900}
10901
Chris Lattnercf5008a2007-11-06 21:52:06 +000010902/// PHIsEqualValue - Return true if this phi node is always equal to
10903/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10904/// z = some value; x = phi (y, z); y = phi (x, z)
10905static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10906 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10907 // See if we already saw this PHI node.
10908 if (!ValueEqualPHIs.insert(PN))
10909 return true;
10910
10911 // Don't scan crazily complex things.
10912 if (ValueEqualPHIs.size() == 16)
10913 return false;
10914
10915 // Scan the operands to see if they are either phi nodes or are equal to
10916 // the value.
10917 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10918 Value *Op = PN->getIncomingValue(i);
10919 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10920 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10921 return false;
10922 } else if (Op != NonPhiInVal)
10923 return false;
10924 }
10925
10926 return true;
10927}
10928
10929
Chris Lattner473945d2002-05-06 18:06:38 +000010930// PHINode simplification
10931//
Chris Lattner7e708292002-06-25 16:13:24 +000010932Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010933 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010934 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010935
Owen Anderson7e057142006-07-10 22:03:18 +000010936 if (Value *V = PN.hasConstantValue())
10937 return ReplaceInstUsesWith(PN, V);
10938
Owen Anderson7e057142006-07-10 22:03:18 +000010939 // If all PHI operands are the same operation, pull them through the PHI,
10940 // reducing code size.
10941 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010942 isa<Instruction>(PN.getIncomingValue(1)) &&
10943 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10944 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10945 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10946 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010947 PN.getIncomingValue(0)->hasOneUse())
10948 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10949 return Result;
10950
10951 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10952 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10953 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010954 if (PN.hasOneUse()) {
10955 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10956 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010957 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010958 PotentiallyDeadPHIs.insert(&PN);
10959 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010960 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010961 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010962
10963 // If this phi has a single use, and if that use just computes a value for
10964 // the next iteration of a loop, delete the phi. This occurs with unused
10965 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10966 // common case here is good because the only other things that catch this
10967 // are induction variable analysis (sometimes) and ADCE, which is only run
10968 // late.
10969 if (PHIUser->hasOneUse() &&
10970 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10971 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010972 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010973 }
10974 }
Owen Anderson7e057142006-07-10 22:03:18 +000010975
Chris Lattnercf5008a2007-11-06 21:52:06 +000010976 // We sometimes end up with phi cycles that non-obviously end up being the
10977 // same value, for example:
10978 // z = some value; x = phi (y, z); y = phi (x, z)
10979 // where the phi nodes don't necessarily need to be in the same block. Do a
10980 // quick check to see if the PHI node only contains a single non-phi value, if
10981 // so, scan to see if the phi cycle is actually equal to that value.
10982 {
10983 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10984 // Scan for the first non-phi operand.
10985 while (InValNo != NumOperandVals &&
10986 isa<PHINode>(PN.getIncomingValue(InValNo)))
10987 ++InValNo;
10988
10989 if (InValNo != NumOperandVals) {
10990 Value *NonPhiInVal = PN.getOperand(InValNo);
10991
10992 // Scan the rest of the operands to see if there are any conflicts, if so
10993 // there is no need to recursively scan other phis.
10994 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10995 Value *OpVal = PN.getIncomingValue(InValNo);
10996 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10997 break;
10998 }
10999
11000 // If we scanned over all operands, then we have one unique value plus
11001 // phi values. Scan PHI nodes to see if they all merge in each other or
11002 // the value.
11003 if (InValNo == NumOperandVals) {
11004 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11005 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11006 return ReplaceInstUsesWith(PN, NonPhiInVal);
11007 }
11008 }
11009 }
Chris Lattner60921c92003-12-19 05:58:40 +000011010 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011011}
11012
Chris Lattner7e708292002-06-25 16:13:24 +000011013Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011014 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011015 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011016 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011017 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011018 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011019
Chris Lattnere87597f2004-10-16 18:11:37 +000011020 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011021 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011022
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011023 bool HasZeroPointerIndex = false;
11024 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11025 HasZeroPointerIndex = C->isNullValue();
11026
11027 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011028 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011029
Chris Lattner28977af2004-04-05 01:30:19 +000011030 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011031 if (TD) {
11032 bool MadeChange = false;
11033 unsigned PtrSize = TD->getPointerSizeInBits();
11034
11035 gep_type_iterator GTI = gep_type_begin(GEP);
11036 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11037 I != E; ++I, ++GTI) {
11038 if (!isa<SequentialType>(*GTI)) continue;
11039
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011040 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011041 // to what we need. If narrower, sign-extend it to what we need. This
11042 // explicit cast can make subsequent optimizations more obvious.
11043 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11044
11045 if (OpBits == PtrSize)
11046 continue;
11047
11048 Instruction::CastOps Opc =
11049 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11050 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11051 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011052 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011053 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011054 }
Chris Lattner28977af2004-04-05 01:30:19 +000011055
Chris Lattner90ac28c2002-08-02 19:29:35 +000011056 // Combine Indices - If the source pointer to this getelementptr instruction
11057 // is a getelementptr instruction, combine the indices of the two
11058 // getelementptr instructions into a single instruction.
11059 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011060 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011061 // Note that if our source is a gep chain itself that we wait for that
11062 // chain to be resolved before we perform this transformation. This
11063 // avoids us creating a TON of code in some cases.
11064 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011065 if (GetElementPtrInst *SrcGEP =
11066 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11067 if (SrcGEP->getNumOperands() == 2)
11068 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011069
Chris Lattner72588fc2007-02-15 22:48:32 +000011070 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011071
11072 // Find out whether the last index in the source GEP is a sequential idx.
11073 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011074 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11075 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011076 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011077
Chris Lattner90ac28c2002-08-02 19:29:35 +000011078 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011079 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011080 // Replace: gep (gep %P, long B), long A, ...
11081 // With: T = long A+B; gep %P, T, ...
11082 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011083 Value *Sum;
11084 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11085 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011086 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011087 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011088 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011089 Sum = SO1;
11090 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011091 // If they aren't the same type, then the input hasn't been processed
11092 // by the loop above yet (which canonicalizes sequential index types to
11093 // intptr_t). Just avoid transforming this until the input has been
11094 // normalized.
11095 if (SO1->getType() != GO1->getType())
11096 return 0;
Chris Lattner620ce142004-05-07 22:09:22 +000011097 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Chris Lattnerccf4b342009-08-30 04:49:01 +000011098 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011099 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011100 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011101 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011102 }
Chris Lattner28977af2004-04-05 01:30:19 +000011103 }
Chris Lattner620ce142004-05-07 22:09:22 +000011104
Chris Lattnerab984842009-08-30 05:30:55 +000011105 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011106 if (Src->getNumOperands() == 2) {
11107 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011108 GEP.setOperand(1, Sum);
11109 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011110 }
Chris Lattnerab984842009-08-30 05:30:55 +000011111 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011112 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011113 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011114 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011115 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011116 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011117 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011118 Indices.append(Src->op_begin()+1, Src->op_end());
11119 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011120 }
11121
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011122 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000011123 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011124 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011125 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011126 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011127 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11128 return NewGEP;
11129 }
Chris Lattner6e24d832009-08-30 05:00:50 +000011130 }
11131
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011132 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11133 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011134 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11135
11136 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011137 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11138 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011139 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011140 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11141 // into : GEP i8* X, ...
11142 //
Chris Lattnereed48272005-09-13 00:40:14 +000011143 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011144 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11145 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011146 if (const ArrayType *CATy =
11147 dyn_cast<ArrayType>(CPTy->getElementType())) {
11148 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11149 if (CATy->getElementType() == XTy->getElementType()) {
11150 // -> GEP i8* X, ...
11151 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011152 GetElementPtrInst *NewGEP =
11153 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11154 GEP.getName());
11155 if (cast<GEPOperator>(&GEP)->isInBounds())
11156 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11157 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011158 } else if (const ArrayType *XATy =
11159 dyn_cast<ArrayType>(XTy->getElementType())) {
11160 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011161 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011162 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011163 // At this point, we know that the cast source type is a pointer
11164 // to an array of the same type as the destination pointer
11165 // array. Because the array type is never stepped over (there
11166 // is a leading zero) we can fold the cast into this GEP.
11167 GEP.setOperand(0, X);
11168 return &GEP;
11169 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011170 }
11171 }
Chris Lattnereed48272005-09-13 00:40:14 +000011172 } else if (GEP.getNumOperands() == 2) {
11173 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011174 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11175 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011176 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11177 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011178 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011179 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11180 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011181 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011182 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011183 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011184 GetElementPtrInst *NewGEP =
11185 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11186 if (cast<GEPOperator>(&GEP)->isInBounds())
11187 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11188 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011189 // V and GEP are both pointer types --> BitCast
11190 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011191 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011192
11193 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011194 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011195 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011196 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011197
Owen Anderson1d0be152009-08-13 21:58:54 +000011198 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011199 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011200 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011201
11202 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11203 // allow either a mul, shift, or constant here.
11204 Value *NewIdx = 0;
11205 ConstantInt *Scale = 0;
11206 if (ArrayEltSize == 1) {
11207 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011208 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011209 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011210 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011211 Scale = CI;
11212 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11213 if (Inst->getOpcode() == Instruction::Shl &&
11214 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011215 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11216 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011217 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011218 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011219 NewIdx = Inst->getOperand(0);
11220 } else if (Inst->getOpcode() == Instruction::Mul &&
11221 isa<ConstantInt>(Inst->getOperand(1))) {
11222 Scale = cast<ConstantInt>(Inst->getOperand(1));
11223 NewIdx = Inst->getOperand(0);
11224 }
11225 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011226
Chris Lattner7835cdd2005-09-13 18:36:04 +000011227 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011228 // out, perform the transformation. Note, we don't know whether Scale is
11229 // signed or not. We'll use unsigned version of division/modulo
11230 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011231 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011232 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011233 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011234 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011235 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011236 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11237 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011238 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011239 NewIdx = InsertNewInstBefore(Sc, GEP);
11240 }
11241
11242 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011243 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011244 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011245 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011246 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011247 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011248 if (cast<GEPOperator>(&GEP)->isInBounds())
11249 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011250 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11251 // The NewGEP must be pointer typed, so must the old one -> BitCast
11252 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011253 }
11254 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011255 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011256 }
Chris Lattner58407792009-01-09 04:53:57 +000011257
Chris Lattner46cd5a12009-01-09 05:44:56 +000011258 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011259 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011260 /// Y = gep X, <...constant indices...>
11261 /// into a gep of the original struct. This is important for SROA and alias
11262 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011263 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011264 if (TD &&
11265 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011266 // Determine how much the GEP moves the pointer. We are guaranteed to get
11267 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011268 ConstantInt *OffsetV =
11269 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011270 int64_t Offset = OffsetV->getSExtValue();
11271
11272 // If this GEP instruction doesn't move the pointer, just replace the GEP
11273 // with a bitcast of the real input to the dest type.
11274 if (Offset == 0) {
11275 // If the bitcast is of an allocation, and the allocation will be
11276 // converted to match the type of the cast, don't touch this.
11277 if (isa<AllocationInst>(BCI->getOperand(0))) {
11278 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11279 if (Instruction *I = visitBitCast(*BCI)) {
11280 if (I != BCI) {
11281 I->takeName(BCI);
11282 BCI->getParent()->getInstList().insert(BCI, I);
11283 ReplaceInstUsesWith(*BCI, I);
11284 }
11285 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011286 }
Chris Lattner58407792009-01-09 04:53:57 +000011287 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011288 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011289 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011290
11291 // Otherwise, if the offset is non-zero, we need to find out if there is a
11292 // field at Offset in 'A's type. If so, we can pull the cast through the
11293 // GEP.
11294 SmallVector<Value*, 8> NewIndices;
11295 const Type *InTy =
11296 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011297 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011298 Instruction *NGEP =
11299 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11300 NewIndices.end());
11301 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011302 if (cast<GEPOperator>(&GEP)->isInBounds())
11303 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011304 InsertNewInstBefore(NGEP, GEP);
11305 NGEP->takeName(&GEP);
11306 return new BitCastInst(NGEP, GEP.getType());
11307 }
Chris Lattner58407792009-01-09 04:53:57 +000011308 }
11309 }
11310
Chris Lattner8a2a3112001-12-14 16:52:21 +000011311 return 0;
11312}
11313
Chris Lattner0864acf2002-11-04 16:18:53 +000011314Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11315 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011316 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011317 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11318 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011319 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011320 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011321
11322 // Create and insert the replacement instruction...
11323 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011324 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011325 else {
11326 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011327 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011328 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011329
11330 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011331
Chris Lattner0864acf2002-11-04 16:18:53 +000011332 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011333 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011334 //
11335 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011336 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011337
11338 // Now that I is pointing to the first non-allocation-inst in the block,
11339 // insert our getelementptr instruction...
11340 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011341 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011342 Value *Idx[2];
11343 Idx[0] = NullIdx;
11344 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011345 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11346 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011347 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011348
11349 // Now make everything use the getelementptr instead of the original
11350 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011351 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011352 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011353 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011354 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011355 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011356
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011357 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011358 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011359 // Note that we only do this for alloca's, because malloc should allocate
11360 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011361 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011362 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011363
11364 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11365 if (AI.getAlignment() == 0)
11366 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11367 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011368
Chris Lattner0864acf2002-11-04 16:18:53 +000011369 return 0;
11370}
11371
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011372Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11373 Value *Op = FI.getOperand(0);
11374
Chris Lattner17be6352004-10-18 02:59:09 +000011375 // free undef -> unreachable.
11376 if (isa<UndefValue>(Op)) {
11377 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011378 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011379 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011380 return EraseInstFromFunction(FI);
11381 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011382
Chris Lattner6160e852004-02-28 04:57:37 +000011383 // If we have 'free null' delete the instruction. This can happen in stl code
11384 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011385 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011386 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011387
11388 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11389 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11390 FI.setOperand(0, CI->getOperand(0));
11391 return &FI;
11392 }
11393
11394 // Change free (gep X, 0,0,0,0) into free(X)
11395 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11396 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011397 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011398 FI.setOperand(0, GEPI->getOperand(0));
11399 return &FI;
11400 }
11401 }
11402
11403 // Change free(malloc) into nothing, if the malloc has a single use.
11404 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11405 if (MI->hasOneUse()) {
11406 EraseInstFromFunction(FI);
11407 return EraseInstFromFunction(*MI);
11408 }
Chris Lattner6160e852004-02-28 04:57:37 +000011409
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011410 return 0;
11411}
11412
11413
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011414/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011415static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011416 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011417 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011418 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011419 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011420
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011421 if (TD) {
11422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11423 // Instead of loading constant c string, use corresponding integer value
11424 // directly if string length is small enough.
11425 std::string Str;
11426 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11427 unsigned len = Str.length();
11428 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11429 unsigned numBits = Ty->getPrimitiveSizeInBits();
11430 // Replace LI with immediate integer store.
11431 if ((numBits >> 3) == len + 1) {
11432 APInt StrVal(numBits, 0);
11433 APInt SingleChar(numBits, 0);
11434 if (TD->isLittleEndian()) {
11435 for (signed i = len-1; i >= 0; i--) {
11436 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11437 StrVal = (StrVal << 8) | SingleChar;
11438 }
11439 } else {
11440 for (unsigned i = 0; i < len; i++) {
11441 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11442 StrVal = (StrVal << 8) | SingleChar;
11443 }
11444 // Append NULL at the end.
11445 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011446 StrVal = (StrVal << 8) | SingleChar;
11447 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011448 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011449 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011450 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011451 }
11452 }
11453 }
11454
Mon P Wang6753f952009-02-07 22:19:29 +000011455 const PointerType *DestTy = cast<PointerType>(CI->getType());
11456 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011457 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011458
11459 // If the address spaces don't match, don't eliminate the cast.
11460 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11461 return 0;
11462
Chris Lattnerb89e0712004-07-13 01:49:43 +000011463 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011464
Reid Spencer42230162007-01-22 05:51:25 +000011465 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011466 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011467 // If the source is an array, the code below will not succeed. Check to
11468 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11469 // constants.
11470 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11471 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11472 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011473 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011474 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011475 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011476 SrcTy = cast<PointerType>(CastOp->getType());
11477 SrcPTy = SrcTy->getElementType();
11478 }
11479
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011480 if (IC.getTargetData() &&
11481 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011482 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011483 // Do not allow turning this into a load of an integer, which is then
11484 // casted to a pointer, this pessimizes pointer analysis a lot.
11485 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011486 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11487 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011488
Chris Lattnerf9527852005-01-31 04:50:46 +000011489 // Okay, we are casting from one integer or pointer type to another of
11490 // the same size. Instead of casting the pointer before the load, cast
11491 // the result of the loaded value.
11492 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11493 CI->getName(),
11494 LI.isVolatile()),LI);
11495 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011496 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011497 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011498 }
11499 }
11500 return 0;
11501}
11502
Chris Lattner833b8a42003-06-26 05:06:25 +000011503Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11504 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011505
Dan Gohman9941f742007-07-20 16:34:21 +000011506 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011507 if (TD) {
11508 unsigned KnownAlign =
11509 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11510 if (KnownAlign >
11511 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11512 LI.getAlignment()))
11513 LI.setAlignment(KnownAlign);
11514 }
Dan Gohman9941f742007-07-20 16:34:21 +000011515
Chris Lattner37366c12005-05-01 04:24:53 +000011516 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011517 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011518 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011519 return Res;
11520
11521 // None of the following transforms are legal for volatile loads.
11522 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011523
Dan Gohman2276a7b2008-10-15 23:19:35 +000011524 // Do really simple store-to-load forwarding and load CSE, to catch cases
11525 // where there are several consequtive memory accesses to the same location,
11526 // separated by a few arithmetic operations.
11527 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011528 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11529 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011530
Christopher Lambb15147e2007-12-29 07:56:53 +000011531 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11532 const Value *GEPI0 = GEPI->getOperand(0);
11533 // TODO: Consider a target hook for valid address spaces for this xform.
11534 if (isa<ConstantPointerNull>(GEPI0) &&
11535 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011536 // Insert a new store to null instruction before the load to indicate
11537 // that this code is not reachable. We do this instead of inserting
11538 // an unreachable instruction directly because we cannot modify the
11539 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011540 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011541 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011542 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011543 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011544 }
Chris Lattner37366c12005-05-01 04:24:53 +000011545
Chris Lattnere87597f2004-10-16 18:11:37 +000011546 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011547 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011548 // TODO: Consider a target hook for valid address spaces for this xform.
11549 if (isa<UndefValue>(C) || (C->isNullValue() &&
11550 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011551 // Insert a new store to null instruction before the load to indicate that
11552 // this code is not reachable. We do this instead of inserting an
11553 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011554 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011555 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011556 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011557 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011558
Chris Lattnere87597f2004-10-16 18:11:37 +000011559 // Instcombine load (constant global) into the value loaded.
11560 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011561 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011562 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011563
Chris Lattnere87597f2004-10-16 18:11:37 +000011564 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011565 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011566 if (CE->getOpcode() == Instruction::GetElementPtr) {
11567 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011568 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011569 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011570 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011571 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011572 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011573 if (CE->getOperand(0)->isNullValue()) {
11574 // Insert a new store to null instruction before the load to indicate
11575 // that this code is not reachable. We do this instead of inserting
11576 // an unreachable instruction directly because we cannot modify the
11577 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011578 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011579 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011580 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011581 }
11582
Reid Spencer3da59db2006-11-27 01:05:10 +000011583 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011584 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011585 return Res;
11586 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011587 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011588 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011589
11590 // If this load comes from anywhere in a constant global, and if the global
11591 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011592 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011593 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011594 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011595 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011596 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011597 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011598 }
11599 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011600
Chris Lattner37366c12005-05-01 04:24:53 +000011601 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011602 // Change select and PHI nodes to select values instead of addresses: this
11603 // helps alias analysis out a lot, allows many others simplifications, and
11604 // exposes redundancy in the code.
11605 //
11606 // Note that we cannot do the transformation unless we know that the
11607 // introduced loads cannot trap! Something like this is valid as long as
11608 // the condition is always false: load (select bool %C, int* null, int* %G),
11609 // but it would not be valid if we transformed it to load from null
11610 // unconditionally.
11611 //
11612 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11613 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011614 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11615 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011616 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011617 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011618 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011619 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011620 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011621 }
11622
Chris Lattner684fe212004-09-23 15:46:00 +000011623 // load (select (cond, null, P)) -> load P
11624 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11625 if (C->isNullValue()) {
11626 LI.setOperand(0, SI->getOperand(2));
11627 return &LI;
11628 }
11629
11630 // load (select (cond, P, null)) -> load P
11631 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11632 if (C->isNullValue()) {
11633 LI.setOperand(0, SI->getOperand(1));
11634 return &LI;
11635 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011636 }
11637 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011638 return 0;
11639}
11640
Reid Spencer55af2b52007-01-19 21:20:31 +000011641/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011642/// when possible. This makes it generally easy to do alias analysis and/or
11643/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011644static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11645 User *CI = cast<User>(SI.getOperand(1));
11646 Value *CastOp = CI->getOperand(0);
11647
11648 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011649 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11650 if (SrcTy == 0) return 0;
11651
11652 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011653
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011654 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11655 return 0;
11656
Chris Lattner3914f722009-01-24 01:00:13 +000011657 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11658 /// to its first element. This allows us to handle things like:
11659 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11660 /// on 32-bit hosts.
11661 SmallVector<Value*, 4> NewGEPIndices;
11662
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011663 // If the source is an array, the code below will not succeed. Check to
11664 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11665 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011666 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11667 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011668 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011669 NewGEPIndices.push_back(Zero);
11670
11671 while (1) {
11672 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011673 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011674 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011675 NewGEPIndices.push_back(Zero);
11676 SrcPTy = STy->getElementType(0);
11677 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11678 NewGEPIndices.push_back(Zero);
11679 SrcPTy = ATy->getElementType();
11680 } else {
11681 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011682 }
Chris Lattner3914f722009-01-24 01:00:13 +000011683 }
11684
Owen Andersondebcb012009-07-29 22:17:13 +000011685 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011686 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011687
11688 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11689 return 0;
11690
Chris Lattner71759c42009-01-16 20:12:52 +000011691 // If the pointers point into different address spaces or if they point to
11692 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011693 if (!IC.getTargetData() ||
11694 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011695 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011696 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11697 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011698 return 0;
11699
11700 // Okay, we are casting from one integer or pointer type to another of
11701 // the same size. Instead of casting the pointer before
11702 // the store, cast the value to be stored.
11703 Value *NewCast;
11704 Value *SIOp0 = SI.getOperand(0);
11705 Instruction::CastOps opcode = Instruction::BitCast;
11706 const Type* CastSrcTy = SIOp0->getType();
11707 const Type* CastDstTy = SrcPTy;
11708 if (isa<PointerType>(CastDstTy)) {
11709 if (CastSrcTy->isInteger())
11710 opcode = Instruction::IntToPtr;
11711 } else if (isa<IntegerType>(CastDstTy)) {
11712 if (isa<PointerType>(SIOp0->getType()))
11713 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011714 }
Chris Lattner3914f722009-01-24 01:00:13 +000011715
11716 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11717 // emit a GEP to index into its first field.
11718 if (!NewGEPIndices.empty()) {
11719 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011720 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011721 NewGEPIndices.size());
11722 else
11723 CastOp = IC.InsertNewInstBefore(
11724 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11725 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011726 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011727 }
11728
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011729 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011730 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011731 else
11732 NewCast = IC.InsertNewInstBefore(
11733 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11734 SI);
11735 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011736}
11737
Chris Lattner4aebaee2008-11-27 08:56:30 +000011738/// equivalentAddressValues - Test if A and B will obviously have the same
11739/// value. This includes recognizing that %t0 and %t1 will have the same
11740/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011741/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011742/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011743/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011744/// %t2 = load i32* %t1
11745///
11746static bool equivalentAddressValues(Value *A, Value *B) {
11747 // Test if the values are trivially equivalent.
11748 if (A == B) return true;
11749
11750 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011751 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11752 // its only used to compare two uses within the same basic block, which
11753 // means that they'll always either have the same value or one of them
11754 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011755 if (isa<BinaryOperator>(A) ||
11756 isa<CastInst>(A) ||
11757 isa<PHINode>(A) ||
11758 isa<GetElementPtrInst>(A))
11759 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011760 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011761 return true;
11762
11763 // Otherwise they may not be equivalent.
11764 return false;
11765}
11766
Dale Johannesen4945c652009-03-03 21:26:39 +000011767// If this instruction has two uses, one of which is a llvm.dbg.declare,
11768// return the llvm.dbg.declare.
11769DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11770 if (!V->hasNUses(2))
11771 return 0;
11772 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11773 UI != E; ++UI) {
11774 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11775 return DI;
11776 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11777 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11778 return DI;
11779 }
11780 }
11781 return 0;
11782}
11783
Chris Lattner2f503e62005-01-31 05:36:43 +000011784Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11785 Value *Val = SI.getOperand(0);
11786 Value *Ptr = SI.getOperand(1);
11787
11788 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011789 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011790 ++NumCombined;
11791 return 0;
11792 }
Chris Lattner836692d2007-01-15 06:51:56 +000011793
11794 // If the RHS is an alloca with a single use, zapify the store, making the
11795 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011796 // If the RHS is an alloca with a two uses, the other one being a
11797 // llvm.dbg.declare, zapify the store and the declare, making the
11798 // alloca dead. We must do this to prevent declare's from affecting
11799 // codegen.
11800 if (!SI.isVolatile()) {
11801 if (Ptr->hasOneUse()) {
11802 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011803 EraseInstFromFunction(SI);
11804 ++NumCombined;
11805 return 0;
11806 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011807 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11808 if (isa<AllocaInst>(GEP->getOperand(0))) {
11809 if (GEP->getOperand(0)->hasOneUse()) {
11810 EraseInstFromFunction(SI);
11811 ++NumCombined;
11812 return 0;
11813 }
11814 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11815 EraseInstFromFunction(*DI);
11816 EraseInstFromFunction(SI);
11817 ++NumCombined;
11818 return 0;
11819 }
11820 }
11821 }
11822 }
11823 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11824 EraseInstFromFunction(*DI);
11825 EraseInstFromFunction(SI);
11826 ++NumCombined;
11827 return 0;
11828 }
Chris Lattner836692d2007-01-15 06:51:56 +000011829 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011830
Dan Gohman9941f742007-07-20 16:34:21 +000011831 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011832 if (TD) {
11833 unsigned KnownAlign =
11834 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11835 if (KnownAlign >
11836 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11837 SI.getAlignment()))
11838 SI.setAlignment(KnownAlign);
11839 }
Dan Gohman9941f742007-07-20 16:34:21 +000011840
Dale Johannesenacb51a32009-03-03 01:43:03 +000011841 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011842 // stores to the same location, separated by a few arithmetic operations. This
11843 // situation often occurs with bitfield accesses.
11844 BasicBlock::iterator BBI = &SI;
11845 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11846 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011847 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011848 // Don't count debug info directives, lest they affect codegen,
11849 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11850 // It is necessary for correctness to skip those that feed into a
11851 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011852 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011853 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011854 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011855 continue;
11856 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011857
11858 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11859 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011860 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11861 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011862 ++NumDeadStore;
11863 ++BBI;
11864 EraseInstFromFunction(*PrevSI);
11865 continue;
11866 }
11867 break;
11868 }
11869
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011870 // If this is a load, we have to stop. However, if the loaded value is from
11871 // the pointer we're loading and is producing the pointer we're storing,
11872 // then *this* store is dead (X = load P; store X -> P).
11873 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011874 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11875 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011876 EraseInstFromFunction(SI);
11877 ++NumCombined;
11878 return 0;
11879 }
11880 // Otherwise, this is a load from some other location. Stores before it
11881 // may not be dead.
11882 break;
11883 }
11884
Chris Lattner9ca96412006-02-08 03:25:32 +000011885 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011886 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011887 break;
11888 }
11889
11890
11891 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011892
11893 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011894 if (isa<ConstantPointerNull>(Ptr) &&
11895 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011896 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011897 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011898 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011899 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011900 ++NumCombined;
11901 }
11902 return 0; // Do not modify these!
11903 }
11904
11905 // store undef, Ptr -> noop
11906 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011907 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011908 ++NumCombined;
11909 return 0;
11910 }
11911
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011912 // If the pointer destination is a cast, see if we can fold the cast into the
11913 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011914 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011915 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11916 return Res;
11917 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011918 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011919 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11920 return Res;
11921
Chris Lattner408902b2005-09-12 23:23:25 +000011922
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011923 // If this store is the last instruction in the basic block (possibly
11924 // excepting debug info instructions and the pointer bitcasts that feed
11925 // into them), and if the block ends with an unconditional branch, try
11926 // to move it to the successor block.
11927 BBI = &SI;
11928 do {
11929 ++BBI;
11930 } while (isa<DbgInfoIntrinsic>(BBI) ||
11931 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011932 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011933 if (BI->isUnconditional())
11934 if (SimplifyStoreAtEndOfBlock(SI))
11935 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011936
Chris Lattner2f503e62005-01-31 05:36:43 +000011937 return 0;
11938}
11939
Chris Lattner3284d1f2007-04-15 00:07:55 +000011940/// SimplifyStoreAtEndOfBlock - Turn things like:
11941/// if () { *P = v1; } else { *P = v2 }
11942/// into a phi node with a store in the successor.
11943///
Chris Lattner31755a02007-04-15 01:02:18 +000011944/// Simplify things like:
11945/// *P = v1; if () { *P = v2; }
11946/// into a phi node with a store in the successor.
11947///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011948bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11949 BasicBlock *StoreBB = SI.getParent();
11950
11951 // Check to see if the successor block has exactly two incoming edges. If
11952 // so, see if the other predecessor contains a store to the same location.
11953 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011954 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011955
11956 // Determine whether Dest has exactly two predecessors and, if so, compute
11957 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011958 pred_iterator PI = pred_begin(DestBB);
11959 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011960 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011961 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011962 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011963 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011964 return false;
11965
11966 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011967 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011968 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011969 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011970 }
Chris Lattner31755a02007-04-15 01:02:18 +000011971 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011972 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011973
11974 // Bail out if all the relevant blocks aren't distinct (this can happen,
11975 // for example, if SI is in an infinite loop)
11976 if (StoreBB == DestBB || OtherBB == DestBB)
11977 return false;
11978
Chris Lattner31755a02007-04-15 01:02:18 +000011979 // Verify that the other block ends in a branch and is not otherwise empty.
11980 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011981 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011982 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011983 return false;
11984
Chris Lattner31755a02007-04-15 01:02:18 +000011985 // If the other block ends in an unconditional branch, check for the 'if then
11986 // else' case. there is an instruction before the branch.
11987 StoreInst *OtherStore = 0;
11988 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011989 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011990 // Skip over debugging info.
11991 while (isa<DbgInfoIntrinsic>(BBI) ||
11992 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11993 if (BBI==OtherBB->begin())
11994 return false;
11995 --BBI;
11996 }
11997 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011998 OtherStore = dyn_cast<StoreInst>(BBI);
11999 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12000 return false;
12001 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012002 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012003 // destinations is StoreBB, then we have the if/then case.
12004 if (OtherBr->getSuccessor(0) != StoreBB &&
12005 OtherBr->getSuccessor(1) != StoreBB)
12006 return false;
12007
12008 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012009 // if/then triangle. See if there is a store to the same ptr as SI that
12010 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012011 for (;; --BBI) {
12012 // Check to see if we find the matching store.
12013 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12014 if (OtherStore->getOperand(1) != SI.getOperand(1))
12015 return false;
12016 break;
12017 }
Eli Friedman6903a242008-06-13 22:02:12 +000012018 // If we find something that may be using or overwriting the stored
12019 // value, or if we run out of instructions, we can't do the xform.
12020 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012021 BBI == OtherBB->begin())
12022 return false;
12023 }
12024
12025 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012026 // make sure nothing reads or overwrites the stored value in
12027 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012028 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12029 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012030 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012031 return false;
12032 }
12033 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012034
Chris Lattner31755a02007-04-15 01:02:18 +000012035 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012036 Value *MergedVal = OtherStore->getOperand(0);
12037 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012038 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012039 PN->reserveOperandSpace(2);
12040 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012041 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12042 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012043 }
12044
12045 // Advance to a place where it is safe to insert the new store and
12046 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012047 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012048 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12049 OtherStore->isVolatile()), *BBI);
12050
12051 // Nuke the old stores.
12052 EraseInstFromFunction(SI);
12053 EraseInstFromFunction(*OtherStore);
12054 ++NumCombined;
12055 return true;
12056}
12057
Chris Lattner2f503e62005-01-31 05:36:43 +000012058
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012059Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12060 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012061 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012062 BasicBlock *TrueDest;
12063 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012064 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012065 !isa<Constant>(X)) {
12066 // Swap Destinations and condition...
12067 BI.setCondition(X);
12068 BI.setSuccessor(0, FalseDest);
12069 BI.setSuccessor(1, TrueDest);
12070 return &BI;
12071 }
12072
Reid Spencere4d87aa2006-12-23 06:05:41 +000012073 // Cannonicalize fcmp_one -> fcmp_oeq
12074 FCmpInst::Predicate FPred; Value *Y;
12075 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012076 TrueDest, FalseDest)) &&
12077 BI.getCondition()->hasOneUse())
12078 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12079 FPred == FCmpInst::FCMP_OGE) {
12080 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12081 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12082
12083 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012084 BI.setSuccessor(0, FalseDest);
12085 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012086 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012087 return &BI;
12088 }
12089
12090 // Cannonicalize icmp_ne -> icmp_eq
12091 ICmpInst::Predicate IPred;
12092 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012093 TrueDest, FalseDest)) &&
12094 BI.getCondition()->hasOneUse())
12095 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12096 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12097 IPred == ICmpInst::ICMP_SGE) {
12098 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12099 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12100 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012101 BI.setSuccessor(0, FalseDest);
12102 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012103 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012104 return &BI;
12105 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012106
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012107 return 0;
12108}
Chris Lattner0864acf2002-11-04 16:18:53 +000012109
Chris Lattner46238a62004-07-03 00:26:11 +000012110Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12111 Value *Cond = SI.getCondition();
12112 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12113 if (I->getOpcode() == Instruction::Add)
12114 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12115 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12116 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012117 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012118 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012119 AddRHS));
12120 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012121 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012122 return &SI;
12123 }
12124 }
12125 return 0;
12126}
12127
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012128Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012129 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012130
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012131 if (!EV.hasIndices())
12132 return ReplaceInstUsesWith(EV, Agg);
12133
12134 if (Constant *C = dyn_cast<Constant>(Agg)) {
12135 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012136 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012137
12138 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012139 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012140
12141 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12142 // Extract the element indexed by the first index out of the constant
12143 Value *V = C->getOperand(*EV.idx_begin());
12144 if (EV.getNumIndices() > 1)
12145 // Extract the remaining indices out of the constant indexed by the
12146 // first index
12147 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12148 else
12149 return ReplaceInstUsesWith(EV, V);
12150 }
12151 return 0; // Can't handle other constants
12152 }
12153 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12154 // We're extracting from an insertvalue instruction, compare the indices
12155 const unsigned *exti, *exte, *insi, *inse;
12156 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12157 exte = EV.idx_end(), inse = IV->idx_end();
12158 exti != exte && insi != inse;
12159 ++exti, ++insi) {
12160 if (*insi != *exti)
12161 // The insert and extract both reference distinctly different elements.
12162 // This means the extract is not influenced by the insert, and we can
12163 // replace the aggregate operand of the extract with the aggregate
12164 // operand of the insert. i.e., replace
12165 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12166 // %E = extractvalue { i32, { i32 } } %I, 0
12167 // with
12168 // %E = extractvalue { i32, { i32 } } %A, 0
12169 return ExtractValueInst::Create(IV->getAggregateOperand(),
12170 EV.idx_begin(), EV.idx_end());
12171 }
12172 if (exti == exte && insi == inse)
12173 // Both iterators are at the end: Index lists are identical. Replace
12174 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12175 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12176 // with "i32 42"
12177 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12178 if (exti == exte) {
12179 // The extract list is a prefix of the insert list. i.e. replace
12180 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12181 // %E = extractvalue { i32, { i32 } } %I, 1
12182 // with
12183 // %X = extractvalue { i32, { i32 } } %A, 1
12184 // %E = insertvalue { i32 } %X, i32 42, 0
12185 // by switching the order of the insert and extract (though the
12186 // insertvalue should be left in, since it may have other uses).
12187 Value *NewEV = InsertNewInstBefore(
12188 ExtractValueInst::Create(IV->getAggregateOperand(),
12189 EV.idx_begin(), EV.idx_end()),
12190 EV);
12191 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12192 insi, inse);
12193 }
12194 if (insi == inse)
12195 // The insert list is a prefix of the extract list
12196 // We can simply remove the common indices from the extract and make it
12197 // operate on the inserted value instead of the insertvalue result.
12198 // i.e., replace
12199 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12200 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12201 // with
12202 // %E extractvalue { i32 } { i32 42 }, 0
12203 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12204 exti, exte);
12205 }
12206 // Can't simplify extracts from other values. Note that nested extracts are
12207 // already simplified implicitely by the above (extract ( extract (insert) )
12208 // will be translated into extract ( insert ( extract ) ) first and then just
12209 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012210 return 0;
12211}
12212
Chris Lattner220b0cf2006-03-05 00:22:33 +000012213/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12214/// is to leave as a vector operation.
12215static bool CheapToScalarize(Value *V, bool isConstant) {
12216 if (isa<ConstantAggregateZero>(V))
12217 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012218 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012219 if (isConstant) return true;
12220 // If all elts are the same, we can extract.
12221 Constant *Op0 = C->getOperand(0);
12222 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12223 if (C->getOperand(i) != Op0)
12224 return false;
12225 return true;
12226 }
12227 Instruction *I = dyn_cast<Instruction>(V);
12228 if (!I) return false;
12229
12230 // Insert element gets simplified to the inserted element or is deleted if
12231 // this is constant idx extract element and its a constant idx insertelt.
12232 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12233 isa<ConstantInt>(I->getOperand(2)))
12234 return true;
12235 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12236 return true;
12237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12238 if (BO->hasOneUse() &&
12239 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12240 CheapToScalarize(BO->getOperand(1), isConstant)))
12241 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012242 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12243 if (CI->hasOneUse() &&
12244 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12245 CheapToScalarize(CI->getOperand(1), isConstant)))
12246 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012247
12248 return false;
12249}
12250
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012251/// Read and decode a shufflevector mask.
12252///
12253/// It turns undef elements into values that are larger than the number of
12254/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012255static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12256 unsigned NElts = SVI->getType()->getNumElements();
12257 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12258 return std::vector<unsigned>(NElts, 0);
12259 if (isa<UndefValue>(SVI->getOperand(2)))
12260 return std::vector<unsigned>(NElts, 2*NElts);
12261
12262 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012263 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012264 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12265 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012266 Result.push_back(NElts*2); // undef -> 8
12267 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012268 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012269 return Result;
12270}
12271
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012272/// FindScalarElement - Given a vector and an element number, see if the scalar
12273/// value is already around as a register, for example if it were inserted then
12274/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012275static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012276 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012277 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12278 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012279 unsigned Width = PTy->getNumElements();
12280 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012281 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012282
12283 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012284 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012285 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012286 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012287 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012288 return CP->getOperand(EltNo);
12289 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12290 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012291 if (!isa<ConstantInt>(III->getOperand(2)))
12292 return 0;
12293 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012294
12295 // If this is an insert to the element we are looking for, return the
12296 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012297 if (EltNo == IIElt)
12298 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012299
12300 // Otherwise, the insertelement doesn't modify the value, recurse on its
12301 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012302 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012303 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012304 unsigned LHSWidth =
12305 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012306 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012307 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012308 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012309 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012310 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012311 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012312 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012313 }
12314
12315 // Otherwise, we don't know.
12316 return 0;
12317}
12318
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012319Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012320 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012321 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012322 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012323
Dan Gohman07a96762007-07-16 14:29:03 +000012324 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012325 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012326 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012327
Reid Spencer9d6565a2007-02-15 02:26:10 +000012328 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012329 // If vector val is constant with all elements the same, replace EI with
12330 // that element. When the elements are not identical, we cannot replace yet
12331 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012332 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012333 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012334 if (C->getOperand(i) != op0) {
12335 op0 = 0;
12336 break;
12337 }
12338 if (op0)
12339 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012340 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012341
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012342 // If extracting a specified index from the vector, see if we can recursively
12343 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012344 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012345 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012346 unsigned VectorWidth =
12347 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012348
12349 // If this is extracting an invalid index, turn this into undef, to avoid
12350 // crashing the code below.
12351 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012352 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012353
Chris Lattner867b99f2006-10-05 06:55:50 +000012354 // This instruction only demands the single element from the input vector.
12355 // If the input vector has a single use, simplify it based on this use
12356 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012357 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012358 APInt UndefElts(VectorWidth, 0);
12359 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012360 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012361 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012362 EI.setOperand(0, V);
12363 return &EI;
12364 }
12365 }
12366
Owen Andersond672ecb2009-07-03 00:17:18 +000012367 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012368 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012369
12370 // If the this extractelement is directly using a bitcast from a vector of
12371 // the same number of elements, see if we can find the source element from
12372 // it. In this case, we will end up needing to bitcast the scalars.
12373 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12374 if (const VectorType *VT =
12375 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12376 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012377 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12378 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012379 return new BitCastInst(Elt, EI.getType());
12380 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012381 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012382
Chris Lattner73fa49d2006-05-25 22:53:38 +000012383 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012384 if (I->hasOneUse()) {
12385 // Push extractelement into predecessor operation if legal and
12386 // profitable to do so
12387 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012388 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12389 if (CheapToScalarize(BO, isConstantElt)) {
12390 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012391 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012392 EI.getName()+".lhs");
12393 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012394 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012395 EI.getName()+".rhs");
12396 InsertNewInstBefore(newEI0, EI);
12397 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012398 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012399 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012400 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012401 unsigned AS =
12402 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012403 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wang7c4efa62009-08-13 05:12:13 +000012404 PointerType::get(EI.getType(), AS),*I);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012405 GetElementPtrInst *GEP =
12406 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012407 cast<GEPOperator>(GEP)->setIsInBounds(true);
Mon P Wang7c4efa62009-08-13 05:12:13 +000012408 InsertNewInstBefore(GEP, *I);
12409 LoadInst* Load = new LoadInst(GEP, "tmp");
12410 InsertNewInstBefore(Load, *I);
12411 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012412 }
12413 }
12414 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12415 // Extracting the inserted element?
12416 if (IE->getOperand(2) == EI.getOperand(1))
12417 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12418 // If the inserted and extracted elements are constants, they must not
12419 // be the same value, extract from the pre-inserted value instead.
12420 if (isa<Constant>(IE->getOperand(2)) &&
12421 isa<Constant>(EI.getOperand(1))) {
12422 AddUsesToWorkList(EI);
12423 EI.setOperand(0, IE->getOperand(0));
12424 return &EI;
12425 }
12426 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12427 // If this is extracting an element from a shufflevector, figure out where
12428 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012429 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12430 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012431 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012432 unsigned LHSWidth =
12433 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12434
12435 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012436 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012437 else if (SrcIdx < LHSWidth*2) {
12438 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012439 Src = SVI->getOperand(1);
12440 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012441 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012442 }
Eric Christophera3500da2009-07-25 02:28:41 +000012443 return ExtractElementInst::Create(Src,
Owen Anderson1d0be152009-08-13 21:58:54 +000012444 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012445 }
12446 }
Eli Friedman2451a642009-07-18 23:06:53 +000012447 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012448 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012449 return 0;
12450}
12451
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012452/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12453/// elements from either LHS or RHS, return the shuffle mask and true.
12454/// Otherwise, return false.
12455static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012456 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012457 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012458 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12459 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012460 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012461
12462 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012463 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012464 return true;
12465 } else if (V == LHS) {
12466 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012467 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012468 return true;
12469 } else if (V == RHS) {
12470 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012471 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012472 return true;
12473 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12474 // If this is an insert of an extract from some other vector, include it.
12475 Value *VecOp = IEI->getOperand(0);
12476 Value *ScalarOp = IEI->getOperand(1);
12477 Value *IdxOp = IEI->getOperand(2);
12478
Chris Lattnerd929f062006-04-27 21:14:21 +000012479 if (!isa<ConstantInt>(IdxOp))
12480 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012481 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012482
12483 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12484 // Okay, we can handle this if the vector we are insertinting into is
12485 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012486 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012487 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012488 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012489 return true;
12490 }
12491 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12492 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012493 EI->getOperand(0)->getType() == V->getType()) {
12494 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012495 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012496
12497 // This must be extracting from either LHS or RHS.
12498 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12499 // Okay, we can handle this if the vector we are insertinting into is
12500 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012501 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012502 // If so, update the mask to reflect the inserted value.
12503 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012504 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012505 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012506 } else {
12507 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012508 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012509 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012510
12511 }
12512 return true;
12513 }
12514 }
12515 }
12516 }
12517 }
12518 // TODO: Handle shufflevector here!
12519
12520 return false;
12521}
12522
12523/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12524/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12525/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012526static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012527 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012528 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012529 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012530 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012531 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012532
12533 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012534 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012535 return V;
12536 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012537 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012538 return V;
12539 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12540 // If this is an insert of an extract from some other vector, include it.
12541 Value *VecOp = IEI->getOperand(0);
12542 Value *ScalarOp = IEI->getOperand(1);
12543 Value *IdxOp = IEI->getOperand(2);
12544
12545 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12546 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12547 EI->getOperand(0)->getType() == V->getType()) {
12548 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012549 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12550 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012551
12552 // Either the extracted from or inserted into vector must be RHSVec,
12553 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012554 if (EI->getOperand(0) == RHS || RHS == 0) {
12555 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012556 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012557 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012558 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012559 return V;
12560 }
12561
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012562 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012563 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12564 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012565 // Everything but the extracted element is replaced with the RHS.
12566 for (unsigned i = 0; i != NumElts; ++i) {
12567 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012568 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012569 }
12570 return V;
12571 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012572
12573 // If this insertelement is a chain that comes from exactly these two
12574 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012575 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12576 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012577 return EI->getOperand(0);
12578
Chris Lattnerefb47352006-04-15 01:39:45 +000012579 }
12580 }
12581 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012582 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012583
12584 // Otherwise, can't do anything fancy. Return an identity vector.
12585 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012586 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012587 return V;
12588}
12589
12590Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12591 Value *VecOp = IE.getOperand(0);
12592 Value *ScalarOp = IE.getOperand(1);
12593 Value *IdxOp = IE.getOperand(2);
12594
Chris Lattner599ded12007-04-09 01:11:16 +000012595 // Inserting an undef or into an undefined place, remove this.
12596 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12597 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012598
Chris Lattnerefb47352006-04-15 01:39:45 +000012599 // If the inserted element was extracted from some other vector, and if the
12600 // indexes are constant, try to turn this into a shufflevector operation.
12601 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12602 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12603 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012604 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012605 unsigned ExtractedIdx =
12606 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012607 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012608
12609 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12610 return ReplaceInstUsesWith(IE, VecOp);
12611
12612 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012613 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012614
12615 // If we are extracting a value from a vector, then inserting it right
12616 // back into the same place, just use the input vector.
12617 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12618 return ReplaceInstUsesWith(IE, VecOp);
12619
12620 // We could theoretically do this for ANY input. However, doing so could
12621 // turn chains of insertelement instructions into a chain of shufflevector
12622 // instructions, and right now we do not merge shufflevectors. As such,
12623 // only do this in a situation where it is clear that there is benefit.
12624 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12625 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12626 // the values of VecOp, except then one read from EIOp0.
12627 // Build a new shuffle mask.
12628 std::vector<Constant*> Mask;
12629 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012630 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012631 else {
12632 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012633 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012634 NumVectorElts));
12635 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012636 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012637 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012638 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012639 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012640 }
12641
12642 // If this insertelement isn't used by some other insertelement, turn it
12643 // (and any insertelements it points to), into one big shuffle.
12644 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12645 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012646 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012647 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012648 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012649 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012650 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012651 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 }
12653 }
12654 }
12655
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012656 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12657 APInt UndefElts(VWidth, 0);
12658 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12659 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12660 return &IE;
12661
Chris Lattnerefb47352006-04-15 01:39:45 +000012662 return 0;
12663}
12664
12665
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012666Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12667 Value *LHS = SVI.getOperand(0);
12668 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012669 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012670
12671 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012672
Chris Lattner867b99f2006-10-05 06:55:50 +000012673 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012674 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012675 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012676
Dan Gohman488fbfc2008-09-09 18:11:14 +000012677 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012678
12679 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12680 return 0;
12681
Evan Cheng388df622009-02-03 10:05:09 +000012682 APInt UndefElts(VWidth, 0);
12683 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12684 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012685 LHS = SVI.getOperand(0);
12686 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012687 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012688 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012689
Chris Lattner863bcff2006-05-25 23:48:38 +000012690 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12691 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12692 if (LHS == RHS || isa<UndefValue>(LHS)) {
12693 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012694 // shuffle(undef,undef,mask) -> undef.
12695 return ReplaceInstUsesWith(SVI, LHS);
12696 }
12697
Chris Lattner863bcff2006-05-25 23:48:38 +000012698 // Remap any references to RHS to use LHS.
12699 std::vector<Constant*> Elts;
12700 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012701 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012702 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012703 else {
12704 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012705 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012706 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012707 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012708 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012709 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012710 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012711 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012712 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012713 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012714 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012715 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012716 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012717 LHS = SVI.getOperand(0);
12718 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012719 MadeChange = true;
12720 }
12721
Chris Lattner7b2e27922006-05-26 00:29:06 +000012722 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012723 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012724
Chris Lattner863bcff2006-05-25 23:48:38 +000012725 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12726 if (Mask[i] >= e*2) continue; // Ignore undef values.
12727 // Is this an identity shuffle of the LHS value?
12728 isLHSID &= (Mask[i] == i);
12729
12730 // Is this an identity shuffle of the RHS value?
12731 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012732 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012733
Chris Lattner863bcff2006-05-25 23:48:38 +000012734 // Eliminate identity shuffles.
12735 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12736 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012737
Chris Lattner7b2e27922006-05-26 00:29:06 +000012738 // If the LHS is a shufflevector itself, see if we can combine it with this
12739 // one without producing an unusual shuffle. Here we are really conservative:
12740 // we are absolutely afraid of producing a shuffle mask not in the input
12741 // program, because the code gen may not be smart enough to turn a merged
12742 // shuffle into two specific shuffles: it may produce worse code. As such,
12743 // we only merge two shuffles if the result is one of the two input shuffle
12744 // masks. In this case, merging the shuffles just removes one instruction,
12745 // which we know is safe. This is good for things like turning:
12746 // (splat(splat)) -> splat.
12747 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12748 if (isa<UndefValue>(RHS)) {
12749 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12750
12751 std::vector<unsigned> NewMask;
12752 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12753 if (Mask[i] >= 2*e)
12754 NewMask.push_back(2*e);
12755 else
12756 NewMask.push_back(LHSMask[Mask[i]]);
12757
12758 // If the result mask is equal to the src shuffle or this shuffle mask, do
12759 // the replacement.
12760 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012761 unsigned LHSInNElts =
12762 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012763 std::vector<Constant*> Elts;
12764 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012765 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012766 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012767 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012768 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012769 }
12770 }
12771 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12772 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012773 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012774 }
12775 }
12776 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012777
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012778 return MadeChange ? &SVI : 0;
12779}
12780
12781
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012782
Chris Lattnerea1c4542004-12-08 23:43:58 +000012783
12784/// TryToSinkInstruction - Try to move the specified instruction from its
12785/// current block into the beginning of DestBlock, which can only happen if it's
12786/// safe to move the instruction past all of the instructions between it and the
12787/// end of its block.
12788static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12789 assert(I->hasOneUse() && "Invariants didn't hold!");
12790
Chris Lattner108e9022005-10-27 17:13:11 +000012791 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012792 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012793 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012794
Chris Lattnerea1c4542004-12-08 23:43:58 +000012795 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012796 if (isa<AllocaInst>(I) && I->getParent() ==
12797 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012798 return false;
12799
Chris Lattner96a52a62004-12-09 07:14:34 +000012800 // We can only sink load instructions if there is nothing between the load and
12801 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012802 if (I->mayReadFromMemory()) {
12803 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012804 Scan != E; ++Scan)
12805 if (Scan->mayWriteToMemory())
12806 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012807 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012808
Dan Gohman02dea8b2008-05-23 21:05:58 +000012809 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012810
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012811 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012812 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012813 ++NumSunkInst;
12814 return true;
12815}
12816
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012817
12818/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12819/// all reachable code to the worklist.
12820///
12821/// This has a couple of tricks to make the code faster and more powerful. In
12822/// particular, we constant fold and DCE instructions as we go, to avoid adding
12823/// them to the worklist (this significantly speeds up instcombine on code where
12824/// many instructions are dead or constant). Additionally, if we find a branch
12825/// whose condition is a known constant, we only visit the reachable successors.
12826///
12827static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012828 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012829 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012830 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012831 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012832 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012833
Chris Lattner2c7718a2007-03-23 19:17:18 +000012834 while (!Worklist.empty()) {
12835 BB = Worklist.back();
12836 Worklist.pop_back();
12837
12838 // We have now visited this block! If we've already been here, ignore it.
12839 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012840
12841 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012842 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12843 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012844
Chris Lattner2c7718a2007-03-23 19:17:18 +000012845 // DCE instruction if trivially dead.
12846 if (isInstructionTriviallyDead(Inst)) {
12847 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012848 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012849 Inst->eraseFromParent();
12850 continue;
12851 }
12852
12853 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012854 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012855 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12856 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012857 Inst->replaceAllUsesWith(C);
12858 ++NumConstProp;
12859 Inst->eraseFromParent();
12860 continue;
12861 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012862
Devang Patel7fe1dec2008-11-19 18:56:50 +000012863 // If there are two consecutive llvm.dbg.stoppoint calls then
12864 // it is likely that the optimizer deleted code in between these
12865 // two intrinsics.
12866 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12867 if (DBI_Next) {
12868 if (DBI_Prev
12869 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12870 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012871 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012872 DBI_Prev->eraseFromParent();
12873 }
12874 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012875 } else {
12876 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012877 }
12878
Chris Lattner7a1e9242009-08-30 06:13:40 +000012879 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012880 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012881
12882 // Recursively visit successors. If this is a branch or switch on a
12883 // constant, only visit the reachable successor.
12884 TerminatorInst *TI = BB->getTerminator();
12885 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12886 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12887 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012888 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012889 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012890 continue;
12891 }
12892 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12893 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12894 // See if this is an explicit destination.
12895 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12896 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012897 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012898 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012899 continue;
12900 }
12901
12902 // Otherwise it is the default destination.
12903 Worklist.push_back(SI->getSuccessor(0));
12904 continue;
12905 }
12906 }
12907
12908 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12909 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012910 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012911}
12912
Chris Lattnerec9c3582007-03-03 02:04:50 +000012913bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012914 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012915 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012916
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012917 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12918 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012919
Chris Lattnerb3d59702005-07-07 20:40:38 +000012920 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012921 // Do a depth-first traversal of the function, populate the worklist with
12922 // the reachable instructions. Ignore blocks that are not reachable. Keep
12923 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012924 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012925 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012926
Chris Lattnerb3d59702005-07-07 20:40:38 +000012927 // Do a quick scan over the function. If we find any blocks that are
12928 // unreachable, remove any instructions inside of them. This prevents
12929 // the instcombine code from having to deal with some bad special cases.
12930 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12931 if (!Visited.count(BB)) {
12932 Instruction *Term = BB->getTerminator();
12933 while (Term != BB->begin()) { // Remove instrs bottom-up
12934 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012935
Chris Lattnerbdff5482009-08-23 04:37:46 +000012936 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012937 // A debug intrinsic shouldn't force another iteration if we weren't
12938 // going to do one without it.
12939 if (!isa<DbgInfoIntrinsic>(I)) {
12940 ++NumDeadInst;
12941 Changed = true;
12942 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012943 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012944 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012945 I->eraseFromParent();
12946 }
12947 }
12948 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012949
Chris Lattner873ff012009-08-30 05:55:36 +000012950 while (!Worklist.isEmpty()) {
12951 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012952 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012953
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012954 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012955 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012956 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012957 EraseInstFromFunction(*I);
12958 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012959 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012960 continue;
12961 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012962
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012963 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012964 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012965 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012966
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012967 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012968 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012969 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012970 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012971 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012972 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012973 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012974
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012975 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012976 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012977 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12978 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012979 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12980 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012981 if (NewC != CE) {
12982 i->set(NewC);
12983 Changed = true;
12984 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012985 }
12986
Chris Lattnerea1c4542004-12-08 23:43:58 +000012987 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012988 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012989 BasicBlock *BB = I->getParent();
12990 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12991 if (UserParent != BB) {
12992 bool UserIsSuccessor = false;
12993 // See if the user is one of our successors.
12994 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12995 if (*SI == UserParent) {
12996 UserIsSuccessor = true;
12997 break;
12998 }
12999
13000 // If the user is one of our immediate successors, and if that successor
13001 // only has us as a predecessors (we'd have to split the critical edge
13002 // otherwise), we can keep going.
13003 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13004 next(pred_begin(UserParent)) == pred_end(UserParent))
13005 // Okay, the CFG is simple enough, try to sink this instruction.
13006 Changed |= TryToSinkInstruction(I, UserParent);
13007 }
13008 }
13009
Chris Lattner8a2a3112001-12-14 16:52:21 +000013010 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013011#ifndef NDEBUG
13012 std::string OrigI;
13013#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013014 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013015 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013016 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013017 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013018 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013019 DEBUG(errs() << "IC: Old = " << *I << '\n'
13020 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013021
Chris Lattnerf523d062004-06-09 05:08:07 +000013022 // Everything uses the new instruction now.
13023 I->replaceAllUsesWith(Result);
13024
13025 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013026 Worklist.Add(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013027 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013028
Chris Lattner6934a042007-02-11 01:23:03 +000013029 // Move the name to the new instruction first.
13030 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013031
13032 // Insert the new instruction into the basic block...
13033 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013034 BasicBlock::iterator InsertPos = I;
13035
13036 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13037 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13038 ++InsertPos;
13039
13040 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013041
Chris Lattner7a1e9242009-08-30 06:13:40 +000013042 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013043 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013044#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013045 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13046 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013047#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013048
Chris Lattner90ac28c2002-08-02 19:29:35 +000013049 // If the instruction was modified, it's possible that it is now dead.
13050 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013051 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013052 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013053 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013054 Worklist.Add(I);
Chris Lattnerec9c3582007-03-03 02:04:50 +000013055 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013056 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013057 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013058 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013059 }
13060 }
13061
Chris Lattner873ff012009-08-30 05:55:36 +000013062 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013063 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013064}
13065
Chris Lattnerec9c3582007-03-03 02:04:50 +000013066
13067bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013068 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013069 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013070
Chris Lattnerec9c3582007-03-03 02:04:50 +000013071 bool EverMadeChange = false;
13072
13073 // Iterate while there is work to do.
13074 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013075 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013076 EverMadeChange = true;
13077 return EverMadeChange;
13078}
13079
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013080FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013081 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013082}